Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526import CryptoKitimport Darwinimport Foundationimport Testing
@Suitestruct NameGuardTests { @Test func generationStoresOnlyLowercaseTokenAndPairHashes() throws { try withRepository { fixture in let policy = try fixture.policy() #expect(policy.version == 1) #expect(policy.salt.count == 32) #expect(policy.salt.allSatisfy { "0123456789abcdef".contains($0) }) #expect( policy.always == (try ["quorvex", "zindle pavo"].map { try saltedHash(policy.salt, $0) }.sorted())) #expect(policy.contextual == [try saltedHash(policy.salt, "brindle")]) let text = try String(contentsOf: fixture.hashes, encoding: .utf8).lowercased() for name in ["quorvex", "zindle", "pavo", "brindle"] { #expect(!text.contains(name)) } #expect(policy.always.allSatisfy { $0.count == 64 }) } }
@Test func regenerationRetainsSaltAndContext() throws { try withRepository { fixture in let original = try fixture.policy() try fixture.writePrivate("names.txt", "BRINDLE\nzindle pavo\nQUORVEX\n") try fixture.generate().requireSuccess() #expect(try fixture.policy() == original)
try fixture.writePrivate("names.txt", "quorvex\nzindle pavo\n") try fixture.generate().requireSuccess() let reduced = try fixture.policy() #expect(reduced.salt == original.salt) #expect(reduced.always == original.always) #expect(reduced.contextual.isEmpty) } }
@Test func privateInputCanComeFromEnvironment() throws { try withRepository { fixture in try FileManager.default.removeItem(at: fixture.hashes) let input = try fixture.writePrivate("environment.txt", "QUORVEX\n") try fixture.runGuard( ["generate"], environment: ["PARCEL_NAMES_FILE": input.path] ).requireSuccess() let policy = try fixture.policy() #expect(policy.always == [try saltedHash(policy.salt, "quorvex")]) #expect(policy.contextual.isEmpty) } }
@Test func privateInputDefaultsToIsolatedHome() throws { try withRepository { fixture in try FileManager.default.removeItem(at: fixture.hashes) let input = fixture.home.appendingPathComponent(".config/parcel-dev/blocked-names.txt") try fixture.write(input, "zindle pavo\n") try fixture.runGuard(["generate"]).requireSuccess() let policy = try fixture.policy() #expect(policy.always == [try saltedHash(policy.salt, "zindle pavo")]) } }
@Test func privateInputsInsideRepositoryAreRejectedAfterResolvingSymlinks() throws { try withRepository { fixture in let inside = try fixture.writeTracked("private.txt", "quorvex\n") let alias = fixture.privateDirectory.appendingPathComponent("alias.txt") try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: inside) for path in [inside, alias] { for flag in ["--names-file", "--context-file"] { let arguments = flag == "--names-file" ? ["generate", flag, path.path] : ["generate", "--names-file", fixture.names.path, flag, path.path] let result = try fixture.runGuard(arguments) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("outside the repository")) } } } }
@Test func invalidPrivateInputsFailWithoutChangingPolicy() throws { try withRepository { fixture in let original = try fixture.policy() let missing = fixture.privateDirectory.appendingPathComponent("missing.txt") let missingResult = try fixture.generate(names: missing) #expect(missingResult.status == 2, "\(missingResult.output)") for text in [ "", " \n\t\n", "quorvex\nQUORVEX\n", "zindle pavo\nZINDLE PAVO\n", "one two three\n", "zindle-pavo\n", ] { let input = try fixture.writePrivate("invalid.txt", text) let result = try fixture.generate(names: input) #expect(result.status == 2, "Input: \(text); output: \(result.output)") #expect(try fixture.policy() == original) } } }
@Test func contextualInputMustBeASubset() throws { try withRepository { fixture in let original = try fixture.policy() let input = try fixture.writePrivate("subset.txt", "quorvex\n") let context = try fixture.writePrivate("context.txt", "brindle\n") let result = try fixture.generate(names: input, context: context) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("subset")) #expect(try fixture.policy() == original) } }
@Test func missingPolicyAndAllowlistSurfaceErrors() throws { try withRepository { fixture in for path in [fixture.hashes, fixture.allowlist] { let original = try Data(contentsOf: path) try FileManager.default.removeItem(at: path) let result = try fixture.check() #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Name guard:")) try original.write(to: path) } } }
@Test func corruptHashPoliciesSurfaceErrors() throws { try withRepository { fixture in let original = try fixture.policy() let invalid = [ "not json", "[]", "{}", "{\"version\":true,\"salt\":\"\(original.salt)\",\"always\":[],\"contextual\":[]}", "{\"version\":1,\"salt\":\"invalid\",\"always\":[],\"contextual\":[]}", "{\"version\":1,\"salt\":\"\(original.salt)\",\"always\":[\"not-a-hash\"],\"contextual\":[]}", ] for text in invalid { try fixture.write(fixture.hashes, text) let result = try fixture.check() #expect(result.status == 2, "\(result.output)") } for entries in [[], [original.always[0], original.always[0]]] { try fixture.writeJSON( HashPolicy(version: 1, salt: original.salt, always: entries, contextual: []), to: fixture.hashes) let result = try fixture.check() #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("nonempty with no duplicate")) } } }
@Test func corruptAllowlistsSurfaceErrors() throws { try withRepository { fixture in let hash = String(repeating: "a", count: 64) for text in [ "not json", "[]", "{}", "{\"version\":2,\"entries\":[]}", "{\"version\":1,\"entries\":{}}", "{\"version\":1,\"entries\":[{}]}", "{\"version\":1,\"entries\":[{\"scope\":\"content\",\"source\":\"notes.txt\",\"line_hash\":\"\(hash)\",\"token_hash\":\"\(hash)\",\"reason\":\"Old shape\"}]}", ] { try fixture.write(fixture.allowlist, text) let result = try fixture.check() #expect(result.status == 2, "\(result.output)") } for scope in ["content", "artifact"] { let entry = Allowance( scope: scope, sourceHash: scope == "artifact" ? nil : hash, lineHash: hash, tokenHash: hash, reason: "Exact fixture") try fixture.writeAllowances([entry, entry]) let duplicate = try fixture.check() #expect(duplicate.status == 2, "\(duplicate.output)") #expect(duplicate.output.contains("Duplicate allowlist entry")) } for scope in ["content", "path", "commit"] { try fixture.writeAllowances([ Allowance(scope: scope, sourceHash: nil, lineHash: hash, tokenHash: hash, reason: "Missing source") ]) #expect(try fixture.check().status == 2) } for badEntry in [ Allowance( scope: "unknown", sourceHash: hash, lineHash: hash, tokenHash: hash, reason: "Exact fixture"), Allowance( scope: "content", sourceHash: "invalid", lineHash: hash, tokenHash: hash, reason: "Exact fixture"), Allowance( scope: "content", sourceHash: hash, lineHash: "invalid", tokenHash: hash, reason: "Exact fixture"), Allowance(scope: "content", sourceHash: hash, lineHash: hash, tokenHash: hash, reason: ""), ] { try fixture.writeAllowances([badEntry]) let result = try fixture.check() #expect(result.status == 2, "\(result.output)") } } }
@Test func exactTokensMatchCaseInsensitively() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "quorvex\nQUORVEX\nQuOrVeX\n(quorvex)\n") let report = try fixture.report(status: 1) #expect(report.violations.count == 4) #expect(report.violations.map(\.line) == [1, 2, 3, 4]) #expect(report.violations.map(\.column) == [1, 1, 1, 2]) #expect(report.violations.allSatisfy { $0.scope == "content" && $0.source == "notes.txt" }) } }
@Test func substringsAndCamelCaseAreNotSplit() throws { try withRepository { fixture in try fixture.writeTracked( "notes.txt", "quorvexes prefixquorvex loadQuorvex QuorvexController zindlePavo zindleExtra pavo\n") #expect(try fixture.report().violations.isEmpty) } }
@Test func pairsAcceptWhitespaceHyphensDotsAndNewlines() throws { try withRepository { fixture in for separator in [" ", " ", "\t", "-", ".", "\n", "_", "/"] { try fixture.writeTracked("notes.txt", "ZINDLE\(separator)PaVo\n") let report = try fixture.report(status: 1) #expect(report.violations.count == 1, "Separator: \(separator.debugDescription)") #expect(report.violations.first?.line == 1) #expect(report.violations.first?.column == 1) } try fixture.writeTracked("notes.txt", "zindle, pavo\nzindle unrelated pavo\n") #expect(try fixture.report().violations.isEmpty) } }
@Test func contextualWordsAreAllowedInPlainProse() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "The dog has brindle fur.\nA brindle coat keeps it warm.\n") #expect(try fixture.report().violations.isEmpty) } }
@Test func contextualProductReferencesAreBlocked() throws { try withRepository { fixture in for text in [ "Brindle", "BRINDLE", "app brindle", "brindle app", "wm brindle", "brindle wm", "window manager brindle", "brindle window manager", "like brindle", "inspired by brindle", "open /opt/brindle/config", "visit https://brindle.example/docs", "brindle.app", "brindle.com", "com.example.brindle", "\"example.brindle.product\"", ] { try fixture.writeTracked("notes.txt", text + "\n") let report = try fixture.report(status: 1) #expect(report.violations.count == 1, "Reference: \(text)") } try fixture.writeTracked("brindle/notes.txt", "A plain coat.\n") try fixture.writeTracked("notes.txt", "A plain coat.\n") let report = try fixture.report(status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "path") #expect(report.violations.first?.source == "brindle/notes.txt") } }
@Test func unquotedSwiftMemberAccessIsNotAURL() throws { try withRepository { fixture in try fixture.writeTracked( "Model.swift", "let value = state.brindle.count\nlet next = brindle.next\nlet result = model.brindle.value\n") #expect(try fixture.report().violations.isEmpty) } }
@Test func exactAllowancesAreAppliedAndReported() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "A quorvex example.\n") let initial = try fixture.report(status: 1) let hit = try #require(initial.violations.first) let policy = try fixture.policy() #expect(hit.sourceHash == (try saltedHash(policy.salt, "source\0notes.txt"))) try fixture.writeAllowances([Allowance(hit, reason: "Exact test fixture")]) let stored = try String(contentsOf: fixture.allowlist, encoding: .utf8) #expect(!stored.contains("notes.txt")) #expect(!stored.contains("\"source\"")) let report = try fixture.report() #expect(report.violations.isEmpty) #expect(report.allowed.count == 1) #expect(report.allowed.first?.reason == "Exact test fixture") #expect(report.allowed.first?.tokenHash == hit.tokenHash) #expect(report.allowed.first?.sourceHash == hit.sourceHash) let text = try fixture.check(["--report-allowed"]) try text.requireSuccess() #expect(text.output.contains("notes.txt:1:3: allowed (Exact test fixture")) #expect(text.output.contains("1 allowed hits")) } }
@Test func allowancesCannotCrossSourcesOrScopes() throws { try withRepository { fixture in try fixture.writeTracked("first.txt", "quorvex\n") try fixture.writeTracked("second.txt", "quorvex\n") try fixture.writeTracked("quorvex", "quorvex\n") let initial = try fixture.report(status: 1) let entries = initial.violations.filter { $0.scope == "content" && ["first.txt", "quorvex"].contains($0.source) }.map { Allowance($0, reason: "Exact fixture only") } try #require(entries.count == 2) try fixture.writeAllowances(entries) let report = try fixture.report(status: 1) #expect(report.allowed.count == 2) #expect(report.violations.count == 2) #expect(report.violations.contains { $0.scope == "content" && $0.source == "second.txt" }) #expect(report.violations.contains { $0.scope == "path" && $0.source == "quorvex" }) } }
@Test func allowancesRejectMutationAndOtherNamesOnTheSameLine() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "quorvex and zindle pavo\n") let initial = try fixture.report(status: 1) try #require(initial.violations.count == 2) let single = try #require(initial.violations.first { $0.column == 1 }) try fixture.writeAllowances([Allowance(single, reason: "Only this exact token and line")]) let otherName = try fixture.report(status: 1) #expect(otherName.allowed.count == 1) #expect(otherName.violations.count == 1) #expect(otherName.violations.first?.tokenHash != single.tokenHash)
try fixture.writeTracked("notes.txt", "quorvex and ordinary prose\n") let mutation = try fixture.report(status: 1) #expect(mutation.allowed.isEmpty) #expect(mutation.violations.count == 1) #expect(mutation.violations.first?.tokenHash == single.tokenHash) #expect(mutation.violations.first?.lineHash != single.lineHash) } }
@Test func trackedContentAndPathsAreCheckedButUntrackedTextIsNot() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "quorvex\n") try fixture.writeTracked("zindle-pavo.txt", "Ordinary prose.\n") try fixture.write(fixture.root.appendingPathComponent("untracked.txt"), "quorvex\n") let report = try fixture.report(status: 1) #expect(report.violations.count == 2) #expect(report.violations.contains { $0.scope == "content" && $0.source == "notes.txt" }) #expect(report.violations.contains { $0.scope == "path" && $0.source == "zindle-pavo.txt" }) } }
@Test func stagedChecksUseIndexContentInBothDirections() throws { try withRepository { fixture in let path = try fixture.writeTracked("notes.txt", "quorvex\n") try fixture.write(path, "Ordinary prose.\n") #expect(try fixture.report().violations.isEmpty) #expect(try fixture.report(["--staged"], status: 1).violations.count == 1)
try fixture.git(["add", "--", "notes.txt"]).requireSuccess() try fixture.write(path, "quorvex\n") #expect(try fixture.report(status: 1).violations.count == 1) #expect(try fixture.report(["--staged"]).violations.isEmpty) } }
@Test func stagedChecksReadPolicyFromIndex() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "quorvex\n") let replacement = try fixture.writePrivate("replacement.txt", "brindle\n") try fixture.generate(names: replacement).requireSuccess() #expect(try fixture.report().violations.isEmpty) #expect(try fixture.report(["--staged"], status: 1).violations.count == 1)
try fixture.write(fixture.hashes, "not json") #expect(try fixture.check().status == 2) #expect(try fixture.report(["--staged"], status: 1).violations.count == 1) } }
@Test func stagedChecksReadAllowlistFromIndexInBothDirections() throws { try withRepository { fixture in try fixture.writeTracked("notes.txt", "quorvex\n") let initial = try fixture.report(status: 1) let hit = try #require(initial.violations.first) try fixture.writeAllowances([Allowance(hit, reason: "Exact fixture")]) #expect(try fixture.report().allowed.count == 1) #expect(try fixture.report(["--staged"], status: 1).violations.count == 1)
try fixture.git(["add", "--", "Scripts/name-allowlist.json"]).requireSuccess() try fixture.writeAllowances([]) #expect(try fixture.report(status: 1).violations.count == 1) #expect(try fixture.report(["--staged"]).allowed.count == 1)
try fixture.write(fixture.allowlist, "not json") #expect(try fixture.check().status == 2) #expect(try fixture.report(["--staged"]).allowed.count == 1) } }
@Test func stagedChecksIgnoreUnchangedFilesHistoryAndArtifacts() throws { try withRepository { fixture in try fixture.writeTracked("old.txt", "quorvex\n") try fixture.writeTracked("brindle/old.txt", "Ordinary prose.\n") try fixture.git(["commit", "--quiet", "-m", "Quorvex historical message"]).requireSuccess() for relative in ["Packaging/background.png", "build/background.png", ".build/debug/background.png"] { try fixture.write(fixture.root.appendingPathComponent(relative), "quorvex\0") } let empty = try fixture.report(["--staged"]) #expect(empty.violations.isEmpty) #expect(empty.artifacts == 0) try fixture.writeTracked("new.txt", "Ordinary staged prose.\n") let staged = try fixture.report(["--staged"]) #expect(staged.violations.isEmpty) #expect(staged.artifacts == 0) let full = try fixture.report(status: 1) #expect(Set(full.violations.map(\.scope)) == ["content", "path", "commit", "artifact"]) #expect(full.artifacts == 3) } }
@Test func stagedChecksValidateUnchangedPolicyInputsAndRejectDeletedPolicies() throws { try withRepository { fixture in try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() for path in [fixture.hashes, fixture.allowlist] { let original = try Data(contentsOf: path) try fixture.write(path, "not json") #expect(try fixture.report(["--staged"]).violations.isEmpty) try fixture.git(["add", "--", path.path]).requireSuccess() #expect(try fixture.check(["--staged"]).status == 2) try original.write(to: path) #expect(try fixture.check(["--staged"]).status == 2) try fixture.git(["rm", "--cached", "--force", "--", path.path]).requireSuccess() let missing = try fixture.check(["--staged"]) #expect(missing.status == 2, "\(missing.output)") #expect(missing.output.contains("missing from the index")) try fixture.git(["add", "--", path.path]).requireSuccess() #expect(try fixture.report(["--staged"]).violations.isEmpty) } } }
@Test func stagedChecksScanUnchangedAllowlistReasons() throws { try withRepository { fixture in let hash = String(repeating: "a", count: 64) try fixture.writeAllowances([ Allowance(scope: "content", sourceHash: hash, lineHash: hash, tokenHash: hash, reason: "quorvex") ]) try fixture.git(["add", "--", "Scripts/name-allowlist.json"]).requireSuccess() try fixture.git(["commit", "--quiet", "-m", "Fixture policy"]).requireSuccess() let report = try fixture.report(["--staged"], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.source == "Scripts/name-allowlist.json") #expect(report.violations.first?.scope == "content") } }
@Test func stagedChecksUseIndexedCustomPoliciesAndReadExternalOverrides() throws { try withRepository { fixture in let custom = try fixture.writeTracked( "Policy/alternate.json", String(contentsOf: fixture.hashes, encoding: .utf8)) try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() try fixture.write(custom, "not json") try fixture.writeTracked("notes.txt", "quorvex\n") let customPath = fixture.root.appendingPathComponent("Policy/../Policy/alternate.json").path #expect(try fixture.report(["--staged", "--hashes", customPath], status: 1).violations.count == 1) let externalHashes = try fixture.writePrivate( "policy.json", String(contentsOf: fixture.hashes, encoding: .utf8)) let externalAllowlist = try fixture.writePrivate( "allowlist.json", String(contentsOf: fixture.allowlist, encoding: .utf8)) let arguments = ["--staged", "--hashes", externalHashes.path, "--allowlist", externalAllowlist.path] #expect(try fixture.report(arguments, status: 1).violations.count == 1) try fixture.write(externalHashes, "not json") #expect(try fixture.check(arguments).status == 2) } }
@Test func stagedPolicySymlinksCannotReadExternalWorkingContent() throws { try withRepository { fixture in let external = try fixture.writePrivate( "external.json", String(contentsOf: fixture.hashes, encoding: .utf8)) try FileManager.default.removeItem(at: fixture.hashes) try FileManager.default.createSymbolicLink(at: fixture.hashes, withDestinationURL: external) try fixture.git(["add", "--", "Scripts/name-hashes.json"]).requireSuccess() #expect(try fixture.report().violations.isEmpty) for path in [fixture.hashes.path, fixture.root.path + "/Scripts/../Scripts/name-hashes.json"] { let result = try fixture.check(["--staged", "--hashes", path]) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Name guard:")) } } }
@Test(arguments: [0, 5]) func stagedChecksBatchOnlyChangedBlobsAndPolicies(changedCount: Int) throws { try withRepository { fixture in for index in 0..<128 { try fixture.write( fixture.root.appendingPathComponent("Files/file-\(index).txt"), "Clean file \(index).\n") } try fixture.git(["add", "--", "Files"]).requireSuccess() try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() for index in 0..<changedCount { try fixture.writeTracked("Files/file-\(index).txt", "Changed file \(index).\n") } let requests = fixture.privateDirectory.appendingPathComponent("batch-input") let calls = fixture.privateDirectory.appendingPathComponent("git-calls") let environment = try fixture.interceptGit( """ printf '%s\\n' "$*" >> "$GIT_CALLS" if [[ $1 == cat-file ]]; then /usr/bin/tee "$BATCH_INPUT" | /usr/bin/git "$@" exit $? fi """ ).merging(["BATCH_INPUT": requests.path, "GIT_CALLS": calls.path]) { _, replacement in replacement } let result = try fixture.runGuard(["check", "--staged", "--json"], environment: environment) try result.requireSuccess() let commands = try String(contentsOf: calls, encoding: .utf8).split(separator: "\n") #expect(commands.filter { $0.hasPrefix("cat-file") } == ["cat-file --batch"]) #expect(!commands.contains { $0.hasPrefix("log") }) let objects = try String(contentsOf: requests, encoding: .utf8).split(separator: "\n") #expect(objects.count == changedCount + 2) #expect(Set(objects).count == objects.count) } }
@Test func stagedDeletionsAndRenamesCheckOnlySurvivingPaths() throws { try withRepository { fixture in try fixture.writeTracked("quorvex-old.txt", "Ordinary prose.\n") try fixture.writeTracked("deleted.txt", "quorvex\n") try fixture.git(["commit", "--quiet", "-m", "Fixture base"]).requireSuccess() try fixture.git(["rm", "--", "deleted.txt"]).requireSuccess() try fixture.git(["mv", "--", "quorvex-old.txt", "clean.txt"]).requireSuccess() #expect(try fixture.report(["--staged"]).violations.isEmpty) try fixture.git(["mv", "--", "clean.txt", "brindle-new.txt"]).requireSuccess() let report = try fixture.report(["--staged"], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "path") #expect(report.violations.first?.source == "brindle-new.txt") } }
@Test func stagedBatchHandlesUnusualPathsAndByteLengths() throws { try withRepository { fixture in let paths = ["space name.txt", "line\nbreak\tname.txt", "-leading.txt", "café.txt"] for path in paths { try fixture.writeTracked(path, "Élan.\nquorvex") } try fixture.writeTracked("empty.txt", "") let report = try fixture.report(["--staged"], status: 1) #expect(report.violations.count == paths.count) #expect(Set(report.violations.map(\.source)) == Set(paths)) #expect(report.violations.allSatisfy { $0.scope == "content" && $0.line == 2 && $0.column == 1 }) } }
@Test func stagedSymlinksReadTheIndexedTargetWithoutFollowingIt() throws { try withRepository { fixture in let link = fixture.root.appendingPathComponent("alias") try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "quorvex") try fixture.git(["add", "--", "alias"]).requireSuccess() try FileManager.default.removeItem(at: link) try FileManager.default.createSymbolicLink(atPath: link.path, withDestinationPath: "ordinary") #expect(try fixture.report().violations.isEmpty) let report = try fixture.report(["--staged"], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "content") #expect(report.violations.first?.source == "alias") } }
@Test func indexConflictsAndStagedSubmodulesFailClosed() throws { try withRepository { fixture in try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() let blob = try fixture.git(["rev-parse", "HEAD:Scripts/name-hashes.json"]) try blob.requireSuccess() let object = blob.output.trimmingCharacters(in: .whitespacesAndNewlines) let input = try fixture.writePrivate("index-info", "100644 \(object) 2\tconflict.txt\n") try fixture.run( "/bin/bash", ["-c", "git update-index --index-info < \"$1\"", "fixture", input.path] ).requireSuccess() for arguments in [[], ["--staged"]] { let result = try fixture.check(arguments) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Resolve the index conflict")) } try fixture.git(["update-index", "--force-remove", "--", "conflict.txt"]).requireSuccess() let commit = try fixture.git(["rev-parse", "HEAD"]) try commit.requireSuccess() try fixture.git([ "update-index", "--add", "--cacheinfo", "160000,\(commit.output.trimmingCharacters(in: .whitespacesAndNewlines)),dependency", ]).requireSuccess() for arguments in [[], ["--staged"]] { let result = try fixture.check(arguments) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Submodule contents cannot be checked")) } } }
@Test func missingIndexedObjectsFailClosed() throws { try withRepository { fixture in let missing = String(repeating: "a", count: 40) try fixture.git(["update-index", "--add", "--cacheinfo", "100644,\(missing),missing.txt"]) .requireSuccess() let result = try fixture.check(["--staged"]) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Could not read indexed blob")) } }
@Test(arguments: [ "exit 17", "printf '%s missing\\n' \"$oid\"", "printf '%s commit 0\\n\\n' \"$oid\"", "printf 'wrong blob 0\\n\\n'", "printf '%s blob nope\\n' \"$oid\"", "printf '%s blob 8\\nshort' \"$oid\"", "printf '%s blob 0\\nx' \"$oid\"", ]) func malformedBatchResponsesFailClosed(response: String) throws { try withRepository { fixture in let environment = try fixture.interceptGit( """ if [[ $1 == cat-file ]]; then IFS= read -r oid \(response) exit 0 fi """) let result = try fixture.runGuard(["check", "--staged"], environment: environment) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("failed (17)") || result.output.contains("batch")) } }
@Test func batchTrailingDataFailsClosed() throws { try withRepository { fixture in let environment = try fixture.interceptGit( """ if [[ $1 == cat-file ]]; then /usr/bin/git "$@" printf 'extra' exit 0 fi """) let result = try fixture.runGuard(["check", "--staged"], environment: environment) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Unexpected trailing data")) } }
@Test func stagedChecksRejectExplicitArtifactsAndStillCheckProposedMessages() throws { try withRepository { fixture in let artifact = try fixture.writePrivate("artifact.bin", "quorvex\0") let incompatible = try fixture.check(["--staged", "--artifact", artifact.path]) #expect(incompatible.status == 2, "\(incompatible.output)") #expect(incompatible.output.contains("cannot be combined with --staged")) try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() let message = try fixture.writePrivate("message.txt", "Clean title\n\nquorvex\n") let report = try fixture.report(["--staged", "--commit-msg", message.path], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.source == "proposed-message") #expect(report.violations.first?.line == 3) try FileManager.default.removeItem(at: message) #expect(try fixture.check(["--staged", "--commit-msg", message.path]).status == 2) } }
@Test func fullCommitHistoryIncludesSubjectsAndBodies() throws { try withRepository { fixture in try fixture.git(["commit", "--quiet", "-m", "Quorvex", "-m", "An older zindle pavo reference."]) .requireSuccess() let first = try fixture.git(["rev-parse", "HEAD"]) try first.requireSuccess() let originalCommit = first.output.trimmingCharacters(in: .whitespacesAndNewlines) try fixture.git(["commit", "--quiet", "--allow-empty", "-m", "Clean latest message"]).requireSuccess() let report = try fixture.report(status: 1) #expect(report.violations.count == 2) #expect(report.violations.allSatisfy { $0.scope == "commit" && $0.source == originalCommit }) #expect(report.violations.map(\.line) == [1, 3]) } }
@Test func commitHistoryIncludesOtherBranchesAndCheckpointRefs() throws { try withRepository { fixture in try fixture.git(["commit", "--quiet", "-m", "Clean base"]).requireSuccess() let base = try fixture.git(["rev-parse", "HEAD"]) try base.requireSuccess() let baseOID = base.output.trimmingCharacters(in: .whitespacesAndNewlines) try fixture.git(["checkout", "--quiet", "-b", "other"]).requireSuccess() try fixture.git(["commit", "--quiet", "--allow-empty", "-m", "Quorvex branch message"]) .requireSuccess() try fixture.git(["checkout", "--quiet", "--detach", baseOID]).requireSuccess() try fixture.git(["commit", "--quiet", "--allow-empty", "-m", "Zindle pavo checkpoint"]) .requireSuccess() let checkpoint = try fixture.git(["rev-parse", "HEAD"]) try checkpoint.requireSuccess() try fixture.git([ "update-ref", "refs/checkpoints/fixture", checkpoint.output.trimmingCharacters(in: .whitespacesAndNewlines), ]).requireSuccess() try fixture.git(["checkout", "--quiet", "--detach", baseOID]).requireSuccess() let report = try fixture.report(status: 1) #expect(report.violations.count == 2) #expect(report.violations.allSatisfy { $0.scope == "commit" }) } }
@Test func proposedMessagesIncludeBodiesAndMissingMessagesFail() throws { try withRepository { fixture in let message = try fixture.writePrivate("message.txt", "Clean title\n\nA quorvex reference.\n") let report = try fixture.report(["--commit-msg", message.path], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "commit") #expect(report.violations.first?.source == "proposed-message") #expect(report.violations.first?.line == 3) try FileManager.default.removeItem(at: message) let missing = try fixture.check(["--commit-msg", message.path]) #expect(missing.status == 2, "\(missing.output)") } }
@Test func trackedBinaryStringsAreChecked() throws { try withRepository { fixture in let path = fixture.root.appendingPathComponent("asset.bin") try Data([0, 255] + Array("QuOrVeX".utf8) + [0, 254]).write(to: path) try fixture.git(["add", "--", "asset.bin"]).requireSuccess() let report = try fixture.report(status: 1) #expect(report.artifacts == 0) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "content") #expect(report.violations.first?.source == "asset.bin") #expect(try fixture.report(["--staged"], status: 1).violations.count == 1) } }
@Test func explicitArtifactsAreScannedAndDeduplicated() throws { try withRepository { fixture in let path = fixture.privateDirectory.appendingPathComponent("asset.bin") try Data([0, 255] + Array("quorvex".utf8) + [0, 254]).write(to: path) let report = try fixture.report(["--artifact", path.path, "--artifact", path.path], status: 1) #expect(report.artifacts == 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "artifact") let expectedPath = try canonicalPath(path) #expect(report.violations.first?.source == expectedPath) } }
@Test func packagingBackgroundIsDiscoveredWithoutImageDecoding() throws { try withRepository { fixture in let path = fixture.root.appendingPathComponent("Packaging/background.png") try fixture.write(path, "") try Data([0, 255] + Array("quorvex".utf8) + [0, 254]).write(to: path) let tracked = try fixture.git(["ls-files", "--", "Packaging/background.png"]) try tracked.requireSuccess() #expect(tracked.output.isEmpty) let report = try fixture.report(status: 1) #expect(report.artifacts == 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "artifact") #expect(report.violations.first?.source == "Packaging/background.png") } }
@Test func malformedMachOArtifactSurfacesStringsFailure() throws { try withRepository { fixture in let path = fixture.privateDirectory.appendingPathComponent("malformed.bin") try Data([ 0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]).write(to: path) let result = try fixture.check(["--artifact", path.path]) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("/usr/bin/strings failed (")) #expect(result.output.contains("truncated or malformed object")) } }
@Test func builtMachOProductsAreDiscoveredInBothBuildDirectories() throws { try withRepository { fixture in let source = try fixture.writePrivate( "fixture.c", "#include <stdio.h>\nint main(void) { return puts(\"quorvex\") < 0; }\n") let executable = fixture.privateDirectory.appendingPathComponent("fixture") try fixture.run("/usr/bin/clang", [source.path, "-o", executable.path]).requireSuccess() for relative in [ "build/Product", ".build/debug/Product", ".build/arm64-apple-macosx/debug/Product", ".build/x86_64-apple-macosx/debug/Product", ".build/checkouts/dependency/Product", ".build/repositories/cache/Product", ".build/artifacts/dependency/Product", ".build/plugins/tool/Product", ".build/arm64-apple-macosx/debug/Product.build/Intermediate", ".build/arm64-apple-macosx/debug/Product.dSYM/Contents/Resources/DWARF/Product", ".build/arm64-apple-macosx/Intermediates.noindex/Product", ".build/arm64-apple-macosx/debug/ModuleCache/Product", ".build/debug/index/Product", ] { let destination = fixture.root.appendingPathComponent(relative) try FileManager.default.createDirectory( at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: executable, to: destination) } let report = try fixture.report(status: 1) #expect(report.artifacts == 4) #expect(report.violations.count == 4) #expect(Set(report.violations.map(\.source)) == ["build/Product", ".build/debug/Product"]) #expect(report.violations.filter { $0.source == ".build/debug/Product" }.count == 3) #expect(report.violations.allSatisfy { $0.scope == "artifact" }) } }
@Test func artifactDiscoveryKeepsLibrariesAndSkipsNonproductsAndSymlinks() throws { try withRepository { fixture in let source = try fixture.writePrivate("fixture.c", "const char *label(void) { return \"quorvex\"; }\n") let library = fixture.privateDirectory.appendingPathComponent("fixture.dylib") try fixture.run("/usr/bin/clang", ["-dynamiclib", source.path, "-o", library.path]).requireSuccess() for relative in ["build/libFixture.dylib", ".build/debug/libFixture.so", ".build/debug/Fixture.o"] { let path = fixture.root.appendingPathComponent(relative) try FileManager.default.createDirectory( at: path.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: library, to: path) try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: path.path) } let script = fixture.root.appendingPathComponent("build/helper") try fixture.write(script, "#!/bin/sh\n# quorvex\n") try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path) try FileManager.default.createSymbolicLink( at: fixture.root.appendingPathComponent("build/alias.dylib"), withDestinationURL: library) let report = try fixture.report(status: 1) #expect(report.artifacts == 2) #expect(report.violations.count == 2) #expect(Set(report.violations.map(\.source)) == ["build/libFixture.dylib", ".build/debug/libFixture.so"]) let explicit = try fixture.report( ["--artifact", fixture.root.appendingPathComponent(".build/debug/Fixture.o").path], status: 1) #expect(explicit.artifacts == 3) } }
@Test func missingOrDirectoryArtifactsSurfaceErrors() throws { try withRepository { fixture in for path in [fixture.privateDirectory.appendingPathComponent("missing.bin"), fixture.privateDirectory] { let result = try fixture.check(["--artifact", path.path]) #expect(result.status == 2, "\(result.output)") #expect(result.output.contains("Name guard:")) } } }
@Test func shortBinaryAliasesNeedProductContext() throws { try withRepository { fixture in let names = try fixture.writePrivate("short.txt", "quorvex\nzindle pavo\nbrindle\nqv\nqvx\n") try fixture.generate(names: names).requireSuccess() let path = fixture.privateDirectory.appendingPathComponent("pixels.bin") let suffixes: [[UInt8]] = [[0, 2], [255, 2], []] for text in ["qv", "QV", "qvx", "QVX", " qv ", "!QV!", "qv qvx", "qv unrelated"] { for suffix in suffixes { try Data([1] + Array(text.utf8) + suffix).write(to: path) let report = try fixture.report(["--artifact", path.path]) #expect(report.artifacts == 1) #expect(report.violations.isEmpty) } } for text in [ "qv app", "wm QV", "inspired by qvx", "/opt/qv/config", "https://qv.example", "com.example.qv", ] { try Data([1] + Array(text.utf8) + [0, 2]).write(to: path) let report = try fixture.report(["--artifact", path.path], status: 1) #expect(report.violations.count == 1, "Context: \(text)") #expect(report.violations.first?.scope == "artifact") } try fixture.writeTracked("notes.txt", "qv\nqvx\n") #expect(try fixture.report(status: 1).violations.count == 2) } }
@Test func optimizedMachODataDoesNotCountAsAShortName() throws { try withRepository { fixture in let names = try fixture.writePrivate("short.txt", "qv\n") try fixture.generate(names: names).requireSuccess() let source = try fixture.writePrivate( "fixture.c", "const volatile unsigned char sample[] = {1, 'q', 'v', 0, 2};\nint main(void) { return sample[0]; }\n") let executable = fixture.root.appendingPathComponent(".build/arm64-apple-macosx/Products/Release/Product") try FileManager.default.createDirectory( at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) try fixture.run("/usr/bin/clang", ["-O2", source.path, "-o", executable.path]).requireSuccess() let strings = try fixture.run("/usr/bin/strings", ["-n", "2", executable.path]) try strings.requireSuccess() #expect(strings.output.split(separator: "\n").contains("qv")) let report = try fixture.report() #expect(report.artifacts == 1) #expect(report.violations.isEmpty) } }
@Test func trackedBinaryShortAliasesUseTheSameEvidenceRules() throws { try withRepository { fixture in let names = try fixture.writePrivate("short.txt", "qv\n") try fixture.generate(names: names).requireSuccess() let path = try fixture.writeTracked("asset.bin", "") try Data([0] + Array("QV\0qv app\0".utf8)).write(to: path) try fixture.git(["add", "--", "asset.bin", "Scripts/name-hashes.json"]).requireSuccess() for arguments in [[], ["--staged"]] { let report = try fixture.report(arguments, status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.scope == "content") } } }
@Test func binaryRecordsDoNotFormPairsAcrossTerminators() throws { try withRepository { fixture in let path = fixture.privateDirectory.appendingPathComponent("strings.bin") try Data("zindle\0pavo\0zindle pavo\0".utf8).write(to: path) let report = try fixture.report(["--artifact", path.path], status: 1) #expect(report.violations.count == 1) #expect(report.violations.first?.line == 3) } }
@Test func artifactAllowancesFollowExactStringsAcrossProductPaths() throws { try withRepository { fixture in let source = try fixture.writePrivate( "fixture.c", "#include <stdio.h>\nint main(void) { return puts(\"Brindle\") < 0; }\n") let executable = fixture.privateDirectory.appendingPathComponent("fixture") try fixture.run("/usr/bin/clang", [source.path, "-o", executable.path]).requireSuccess() let initial = try fixture.report(["--artifact", executable.path], status: 1) let hit = try #require(initial.violations.first) try fixture.writeAllowances([Allowance(hit, reason: "Compiled fixture label")]) let paths = [ "build/Product.app/Contents/MacOS/Product", ".build/debug/Product", ".build/release/Product", ".build/arm64-apple-macosx/debug/Product", ".build/x86_64-apple-macosx/release/Product", ".build/arm64-apple-macosx/Products/Debug/Product", ".build/arm64-apple-macosx/Products/Release/Product", ".build/x86_64-apple-macosx/Products/Debug/Product", ".build/x86_64-apple-macosx/Products/Release/Product", ] for relative in paths { let destination = fixture.root.appendingPathComponent(relative) try FileManager.default.createDirectory( at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: executable, to: destination) } let report = try fixture.report(["--artifact", executable.path]) #expect(report.artifacts == paths.count + 1) #expect(report.allowed.count == paths.count + 1) #expect(report.allowed.allSatisfy { $0.lineHash == hit.lineHash && $0.reason == "Compiled fixture label" }) #expect(Set(report.allowed.map(\.sourceHash)).count > 1)
try fixture.writeTracked("notes.txt", "Brindle\n") let changed = fixture.privateDirectory.appendingPathComponent("changed.bin") try Data("Brindle app\0".utf8).write(to: changed) let changedReport = try fixture.report(["--artifact", changed.path], status: 1) #expect(changedReport.violations.count == 2) #expect(changedReport.violations.contains { $0.scope == "content" }) #expect(changedReport.violations.contains { $0.scope == "artifact" }) } }
@Test func artifactAllowancesStillRequireTheExactTokenAndScope() throws { try withRepository { fixture in let path = fixture.privateDirectory.appendingPathComponent("strings.bin") try Data("quorvex and zindle pavo\0".utf8).write(to: path) let initial = try fixture.report(["--artifact", path.path], status: 1) let hit = try #require(initial.violations.first) try fixture.writeAllowances([Allowance(hit, reason: "One compiled token")]) try fixture.writeTracked("quorvex", "quorvex and zindle pavo\n") let message = try fixture.writePrivate("message.txt", "quorvex and zindle pavo\n") let report = try fixture.report(["--artifact", path.path, "--commit-msg", message.path], status: 1) #expect(report.allowed.count == 1) #expect(report.violations.filter { $0.scope == "artifact" }.count == 1) #expect(report.violations.filter { $0.scope == "content" }.count == 2) #expect(report.violations.filter { $0.scope == "commit" }.count == 2) #expect(report.violations.filter { $0.scope == "path" }.count == 1) } }
@Test func sourceScopedArtifactAllowancesRemainSupported() throws { try withRepository { fixture in let first = fixture.privateDirectory.appendingPathComponent("first.bin") let second = fixture.privateDirectory.appendingPathComponent("second.bin") try Data("quorvex\0".utf8).write(to: first) try Data("quorvex\0".utf8).write(to: second) let initial = try fixture.report(["--artifact", first.path], status: 1) let hit = try #require(initial.violations.first) try fixture.writeAllowances([ Allowance( scope: hit.scope, sourceHash: hit.sourceHash, lineHash: hit.lineHash, tokenHash: hit.tokenHash, reason: "One artifact only") ]) let report = try fixture.report(["--artifact", first.path, "--artifact", second.path], status: 1) #expect(report.allowed.count == 1) #expect(report.violations.count == 1) #expect(report.violations.first?.source == (try canonicalPath(second))) } }
@Test func artifactsIgnoreOnlyTheLocalCheckoutPrefix() throws { try withRepository(repositoryName: "quorvex") { fixture in let checkout = try canonicalPath(fixture.root) let path = fixture.privateDirectory.appendingPathComponent("debug.bin") try Data( "\(checkout)/Sources/File.swift\0\(checkout)/Sources/quorvex.swift\0/elsewhere/quorvex/File.swift\0" .utf8 ) .write(to: path) let report = try fixture.report(["--artifact", path.path], status: 1) #expect(report.violations.count == 2) #expect(report.violations.map(\.line) == [2, 3]) try fixture.writeTracked("notes.txt", checkout + "/Sources/File.swift\n") let content = try fixture.report(status: 1) #expect(content.violations.count == 1) #expect(content.violations.first?.scope == "content") } }
@Test func preCommitHookRejectsActualCommitUsingStagedContent() throws { try withRepository { fixture in try fixture.git(["commit", "--quiet", "-s", "-m", "Clean base"]).requireSuccess() let original = try fixture.git(["rev-parse", "HEAD"]) try original.requireSuccess() try fixture.installHooks().requireSuccess() let path = try fixture.writeTracked("notes.txt", "quorvex\n") try fixture.write(path, "Ordinary prose.\n") let commit = try fixture.git(["commit", "--quiet", "-s", "-m", "Clean proposed message"]) #expect(commit.status != 0) #expect(commit.output.contains("blocked name")) let retained = try fixture.git(["rev-parse", "HEAD"]) try retained.requireSuccess() #expect(retained.output == original.output) #expect(try String(contentsOf: path, encoding: .utf8) == "Ordinary prose.\n") let indexed = try fixture.git(["show", ":notes.txt"]) try indexed.requireSuccess() #expect(indexed.output == "quorvex\n") } }
@Test func hookRejectsInitialPartialCommitWithoutChangingItsContents() throws { try withRepository { fixture in try fixture.installHooks().requireSuccess() let path = try fixture.writeTracked("notes.txt", "quorvex\n") try fixture.write(path, "Ordinary prose.\n") let commit = try fixture.git(["commit", "--quiet", "-s", "-m", "Clean proposed message"]) #expect(commit.status != 0) #expect(commit.output.contains("initial commit")) #expect(try fixture.git(["rev-parse", "--verify", "--quiet", "HEAD"]).status != 0) #expect(try String(contentsOf: path, encoding: .utf8) == "Ordinary prose.\n") let indexed = try fixture.git(["show", ":notes.txt"]) try indexed.requireSuccess() #expect(indexed.output == "quorvex\n") } }
@Test func commitMessageHookRejectsActualCommitBody() throws { try withRepository { fixture in try fixture.installHooks().requireSuccess() try fixture.writeTracked("notes.txt", "Ordinary prose.\n") let commit = try fixture.git(["commit", "--quiet", "-s", "-m", "Clean title", "-m", "quorvex"]) #expect(commit.status != 0) #expect(commit.output.contains("proposed-message:3:1: blocked name")) #expect(try fixture.git(["rev-parse", "--verify", "--quiet", "HEAD"]).status != 0) try fixture.git(["commit", "--quiet", "-s", "-m", "Clean message"]).requireSuccess() } }
@Test func commitMessageHookRequiresADCOAndAllowsASignedCommit() throws { try withRepository { fixture in try fixture.installHooks().requireSuccess() let unsigned = try fixture.git(["commit", "--quiet", "-m", "Clean message"]) #expect(unsigned.status != 0) #expect(unsigned.output.contains("Add a DCO sign-off")) #expect(try fixture.git(["rev-parse", "--verify", "--quiet", "HEAD"]).status != 0) try fixture.git(["commit", "--quiet", "-s", "-m", "Clean signed message"]).requireSuccess() } }
@Test func hookInstallationMigratesTheLegacyWorktreeConfiguration() throws { try withRepository { fixture in let legacy = try canonicalPath(fixture.root.appendingPathComponent("Scripts/hooks")) try fixture.git(["config", "--local", "extensions.worktreeConfig", "true"]).requireSuccess() try fixture.git(["config", "--worktree", "core.hooksPath", legacy]).requireSuccess() try fixture.installHooks().requireSuccess() let config = try fixture.git(["config", "--worktree", "--get", "core.hooksPath"]) try config.requireSuccess() #expect( config.output.trimmingCharacters(in: .whitespacesAndNewlines) == (try canonicalPath(fixture.hooksPath()))) #expect(try fixture.git(["config", "--local", "--get", "core.hooksPath"]).status == 1) try fixture.git(["commit", "--quiet", "-s", "-m", "Clean migrated commit"]).requireSuccess() } }
@Test func installerRefusesCustomHookConfigurationAndExistingHooks() throws { try withRepository { fixture in let custom = fixture.privateDirectory.appendingPathComponent("custom-hooks").path try fixture.git(["config", "--local", "core.hooksPath", custom]).requireSuccess() let configured = try fixture.installHooks() #expect(configured.status != 0) #expect(configured.output.contains("Custom hooks already configured")) let retained = try fixture.git(["config", "--get", "core.hooksPath"]) try retained.requireSuccess() #expect(retained.output.trimmingCharacters(in: .whitespacesAndNewlines) == custom) try fixture.git(["config", "--local", "--unset", "core.hooksPath"]).requireSuccess()
for directory in [fixture.root.appendingPathComponent(".git/hooks"), try fixture.hooksPath()] { for name in ["pre-commit", "commit-msg", "pre-push"] { let hook = directory.appendingPathComponent(name) try fixture.write(hook, "#!/bin/sh\nexit 0\n") let existing = try fixture.installHooks() #expect(existing.status != 0) #expect(existing.output.contains("Existing \(name) hook")) #expect(try String(contentsOf: hook, encoding: .utf8) == "#!/bin/sh\nexit 0\n") #expect(try fixture.git(["config", "--get", "core.hooksPath"]).status == 1) try FileManager.default.removeItem(at: hook) } } } }
@Test func hookInstallationRefusesModifiedGeneratedHooks() throws { try withRepository { fixture in try fixture.installHooks().requireSuccess() let hooks = try fixture.hooksPath() let manifest = hooks.appendingPathComponent(".parcel-hook-sha256") let originalManifest = try Data(contentsOf: manifest) for name in ["pre-commit", "commit-msg", "pre-push"] { let path = hooks.appendingPathComponent(name) let original = try Data(contentsOf: path) let modified = original + Data("\n# Local fixture customization.\n".utf8) try modified.write(to: path) let result = try fixture.installHooks() #expect(result.status != 0) #expect(result.output.contains("Existing \(name) hook")) #expect(try Data(contentsOf: path) == modified) #expect(try Data(contentsOf: manifest) == originalManifest) try original.write(to: path) } try fixture.installHooks().requireSuccess() } }
@Test func linkedWorktreeHookInstallationLeavesParentCheckoutUnchanged() throws { try withRepository { fixture in try fixture.git(["add", "--", "Scripts", "lefthook.yml"]).requireSuccess() try fixture.git(["commit", "--quiet", "-s", "-m", "Clean fixture base"]).requireSuccess() let linked = fixture.directory.appendingPathComponent("linked") try fixture.git(["worktree", "add", "--quiet", "--detach", linked.path, "HEAD"]).requireSuccess() try fixture.installHooks(in: linked).requireSuccess() for scope in [[], ["--local"], ["--worktree"]] { let parentConfig = try fixture.git(["config"] + scope + ["--get", "core.hooksPath"]) #expect(parentConfig.status == 1, "\(parentConfig.output)") #expect(parentConfig.output.isEmpty) } let expectedHooks = try canonicalPath(fixture.hooksPath(in: linked)) #expect(!FileManager.default.fileExists(atPath: try fixture.hooksPath().path)) for name in ["pre-commit", "commit-msg", "pre-push"] { #expect(FileManager.default.isExecutableFile(atPath: expectedHooks + "/" + name)) #expect( !FileManager.default.fileExists( atPath: fixture.root.appendingPathComponent(".git/hooks/\(name)").path)) } for scope in [[], ["--worktree"]] { let linkedConfig = try fixture.git( ["-C", linked.path, "config"] + scope + ["--get", "core.hooksPath"]) try linkedConfig.requireSuccess() #expect(linkedConfig.output.trimmingCharacters(in: .whitespacesAndNewlines) == expectedHooks) } } }
@Test func hookInstallationIsIdempotentAndAllowsCleanCommits() throws { try withRepository { fixture in let first = try fixture.installHooks() try first.requireSuccess() #expect(first.output.contains("Installed lefthook checks")) let hooks = try fixture.hooksPath() let installed = try ["pre-commit", "commit-msg", "pre-push"].map { try Data(contentsOf: hooks.appendingPathComponent($0)) } let second = try fixture.installHooks() try second.requireSuccess() #expect(second.output.contains("Installed lefthook checks")) let reinstalled = try ["pre-commit", "commit-msg", "pre-push"].map { try Data(contentsOf: hooks.appendingPathComponent($0)) } #expect(installed == reinstalled) let config = try fixture.git(["config", "--worktree", "--get", "core.hooksPath"]) try config.requireSuccess() let expectedHooks = try canonicalPath(hooks) #expect(config.output.trimmingCharacters(in: .whitespacesAndNewlines) == expectedHooks) let worktreeConfig = try fixture.git(["config", "--local", "--get", "extensions.worktreeConfig"]) try worktreeConfig.requireSuccess() #expect(worktreeConfig.output.trimmingCharacters(in: .whitespacesAndNewlines) == "true") try fixture.git(["commit", "--quiet", "-s", "-m", "Clean fixture commit"]).requireSuccess() } }}
private struct HashPolicy: Codable, Equatable { let version: Int let salt: String let always: [String] let contextual: [String]}
private struct CheckReport: Decodable { let violations: [Hit] let allowed: [Hit] let artifacts: Int}
private struct Hit: Decodable { let scope: String let source: String let sourceHash: String let line: Int let column: Int let lineHash: String let tokenHash: String let reason: String?
enum CodingKeys: String, CodingKey { case scope, source, line, column, reason case sourceHash = "source_hash" case lineHash = "line_hash" case tokenHash = "token_hash" }}
private struct Allowance: Encodable { let scope: String let sourceHash: String? let lineHash: String let tokenHash: String let reason: String
init(scope: String, sourceHash: String?, lineHash: String, tokenHash: String, reason: String) { self.scope = scope self.sourceHash = sourceHash self.lineHash = lineHash self.tokenHash = tokenHash self.reason = reason }
init(_ hit: Hit, reason: String) { self.init( scope: hit.scope, sourceHash: hit.scope == "artifact" ? nil : hit.sourceHash, lineHash: hit.lineHash, tokenHash: hit.tokenHash, reason: reason) }
enum CodingKeys: String, CodingKey { case scope, reason case sourceHash = "source_hash" case lineHash = "line_hash" case tokenHash = "token_hash" }}
private struct Allowlist: Encodable { let version = 1 let entries: [Allowance]}
private struct CommandResult { let status: Int32 let data: Data let output: String
func requireSuccess() throws { try #require(status == 0, "\(output)") }}
private struct RepositoryFixture { static let sourceRoot = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent()
private static let resolvedTool: Result<URL, any Error> = Result { let environment = ProcessInfo.processInfo.environment if let override = environment["PARCEL_DEV_BINARY"] { try #require(!override.isEmpty, "PARCEL_DEV_BINARY must not be empty") } let process = Process() process.environment = environment process.executableURL = URL(fileURLWithPath: "/bin/sh") process.arguments = [sourceRoot.appendingPathComponent("Scripts/parcel-dev.sh").path, "--path"] process.currentDirectoryURL = sourceRoot process.standardInput = FileHandle.nullDevice process.standardError = FileHandle.standardError let output = Pipe() process.standardOutput = output try process.run() let data = output.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() try #require(process.terminationStatus == 0, "Developer tool resolution failed via Scripts/parcel-dev.sh") let text = try #require(String(data: data, encoding: .utf8), "Developer tool path must be UTF-8") try #require(text.hasSuffix("\n"), "Developer tool path must end with a newline") let path = String(text.dropLast()) try #require( !path.isEmpty && !path.contains("\n") && !path.contains("\r") && !path.contains("\0"), "Developer tool resolver must return one path") let binary = URL(fileURLWithPath: path, relativeTo: sourceRoot).resolvingSymlinksInPath() try #require( binary.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true && FileManager.default.isExecutableFile(atPath: binary.path), "Developer tool is not an executable file: \(binary.path)") return binary }
static func developerTool() throws -> URL { try resolvedTool.get() }
private static let pinnedPath: Result<String, any Error> = Result { let process = Process() process.environment = ProcessInfo.processInfo.environment process.executableURL = URL(fileURLWithPath: "/usr/bin/env") process.arguments = ["mise", "env", "--json"] process.currentDirectoryURL = sourceRoot process.standardInput = FileHandle.nullDevice process.standardError = FileHandle.standardError let output = Pipe() process.standardOutput = output try process.run() let data = output.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() try #require(process.terminationStatus == 0, "Could not resolve pinned hook tools through mise") let environment = try JSONDecoder().decode([String: String].self, from: data) return try #require(environment["PATH"], "Pinned tool environment must include PATH") }
let directory: URL let root: URL let privateDirectory: URL let home: URL let environment: [String: String]
var hashes: URL { root.appendingPathComponent("Scripts/name-hashes.json") } var allowlist: URL { root.appendingPathComponent("Scripts/name-allowlist.json") } var names: URL { privateDirectory.appendingPathComponent("names.txt") }
init(directory: URL, repositoryName: String) throws { self.directory = directory root = directory.appendingPathComponent(repositoryName) privateDirectory = directory.appendingPathComponent("private") home = directory.appendingPathComponent("home") environment = [ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin:" + (try Self.pinnedPath.get()), "PARCEL_DEV_BINARY": try Self.developerTool().path, "HOME": home.path, "XDG_CONFIG_HOME": home.appendingPathComponent(".config").path, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_SYSTEM": "/dev/null", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_ATTR_NOSYSTEM": "1", "GIT_TERMINAL_PROMPT": "0", "LANG": "en_US.UTF-8", "LC_ALL": "en_US.UTF-8", ] let template = directory.appendingPathComponent("empty-template") for path in [root, privateDirectory, home, template, root.appendingPathComponent("Scripts/hooks")] { try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) } try git(["init", "--quiet", "--initial-branch=main", "--template=\(template.path)"]).requireSuccess() for (key, value) in [ ("user.name", "Fixture Author"), ("user.email", "fixture@example.invalid"), ("commit.gpgsign", "false"), ("tag.gpgsign", "false"), ("core.autocrlf", "false"), ] { try git(["config", "--local", key, value]).requireSuccess() } for relative in [ "parcel-dev.sh", "check-names.sh", "generate-name-hashes.sh", "setup.sh", "check-commit-message.sh", "check-swift-safety.sh", "staged-checks.sh", ] { let destination = root.appendingPathComponent("Scripts/\(relative)") try FileManager.default.copyItem( at: Self.sourceRoot.appendingPathComponent("Scripts/\(relative)"), to: destination) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: destination.path) } try FileManager.default.copyItem( at: Self.sourceRoot.appendingPathComponent("lefthook.yml"), to: root.appendingPathComponent("lefthook.yml")) try writePrivate("names.txt", "QuOrVeX\nZINDLE PaVo\nbrindle\n") let contextual = try writePrivate("context.txt", "brindle\n") try generate(context: contextual).requireSuccess() try writeAllowances([]) try git(["add", "--", "Scripts/name-hashes.json", "Scripts/name-allowlist.json"]).requireSuccess() }
func run( _ executable: String, _ arguments: [String], workingDirectory: URL? = nil, environment overrides: [String: String] = [:] ) throws -> CommandResult { let log = directory.appendingPathComponent("process-\(UUID().uuidString).log") try Data().write(to: log) let handle = try FileHandle(forWritingTo: log) let process = Process() process.executableURL = URL(fileURLWithPath: executable) process.arguments = arguments process.currentDirectoryURL = workingDirectory ?? root process.environment = environment.merging(overrides) { _, replacement in replacement } process.standardInput = FileHandle.nullDevice process.standardOutput = handle process.standardError = handle do { try process.run() } catch { try handle.close() throw error } process.waitUntilExit() try handle.close() let data = try Data(contentsOf: log) let output = try #require(String(data: data, encoding: .utf8), "Subprocess output must be UTF-8") try FileManager.default.removeItem(at: log) return CommandResult(status: process.terminationStatus, data: data, output: output) }
func git(_ arguments: [String]) throws -> CommandResult { try run("/usr/bin/git", arguments) }
func interceptGit(_ body: String) throws -> [String: String] { let bin = privateDirectory.appendingPathComponent("bin") let wrapper = bin.appendingPathComponent("git") try write(wrapper, "#!/bin/bash\nset -euo pipefail\n" + body + "\nexec /usr/bin/git \"$@\"\n") try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: wrapper.path) return ["PATH": "\(bin.path):/usr/bin:/bin:/usr/sbin:/sbin"] }
func runGuard(_ arguments: [String], environment: [String: String] = [:]) throws -> CommandResult { try run(try Self.developerTool().path, ["name-guard"] + arguments, environment: environment) }
func generate(names input: URL? = nil, context: URL? = nil) throws -> CommandResult { var arguments = ["generate", "--names-file", (input ?? names).path] if let context { arguments += ["--context-file", context.path] } return try runGuard(arguments) }
func check(_ arguments: [String] = []) throws -> CommandResult { try runGuard(["check"] + arguments) }
func report(_ arguments: [String] = [], status: Int32 = 0) throws -> CheckReport { let result = try check(["--json"] + arguments) try #require(result.status == status, "Arguments: \(arguments); output: \(result.output)") return try JSONDecoder().decode(CheckReport.self, from: result.data) }
func installHooks(in workingDirectory: URL? = nil) throws -> CommandResult { let checkout = workingDirectory ?? root return try run( "/bin/bash", [checkout.appendingPathComponent("Scripts/setup.sh").path, "--hooks-only"], workingDirectory: checkout) }
func hooksPath(in workingDirectory: URL? = nil) throws -> URL { let result = try run( "/usr/bin/git", ["rev-parse", "--path-format=absolute", "--git-path", "parcel-hooks"], workingDirectory: workingDirectory) try result.requireSuccess() return URL(fileURLWithPath: result.output.trimmingCharacters(in: .whitespacesAndNewlines)) }
func policy() throws -> HashPolicy { try JSONDecoder().decode(HashPolicy.self, from: Data(contentsOf: hashes)) }
func write(_ path: URL, _ contents: String) throws { try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: true) try contents.write(to: path, atomically: true, encoding: .utf8) }
@discardableResult func writePrivate(_ relative: String, _ contents: String) throws -> URL { let path = privateDirectory.appendingPathComponent(relative) try write(path, contents) return path }
@discardableResult func writeTracked(_ relative: String, _ contents: String) throws -> URL { let path = root.appendingPathComponent(relative) try write(path, contents) try git(["add", "--", relative]).requireSuccess() return path }
func writeJSON<Value: Encodable>(_ value: Value, to path: URL) throws { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(value).write(to: path) }
func writeAllowances(_ entries: [Allowance]) throws { try writeJSON(Allowlist(entries: entries), to: allowlist) }}
private func withRepository(repositoryName: String = "repository", _ body: (RepositoryFixture) throws -> Void) throws { let temporary = FileManager.default.temporaryDirectory .appendingPathComponent("NameGuardTests-\(UUID().uuidString)") try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true) let directory = temporary.resolvingSymlinksInPath() defer { do { try FileManager.default.removeItem(at: directory) } catch { Issue.record("Could not remove fixture at \(directory.path): \(error)") } } try body(RepositoryFixture(directory: directory, repositoryName: repositoryName))}
private func canonicalPath(_ url: URL) throws -> String { let resolved = try #require(realpath(url.path, nil), "Could not canonicalize \(url.path)") defer { free(resolved) } return String(cString: resolved)}
private func saltedHash(_ salt: String, _ value: String) throws -> String { let characters = Array(salt) try #require(characters.count == 32) var data = Data() for index in stride(from: 0, to: characters.count, by: 2) { let byte = try #require(UInt8(String(characters[index...index + 1]), radix: 16)) data.append(byte) } data.append(0) data.append(contentsOf: value.utf8) return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()}