Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238import Foundationimport Security
struct NameOptions { var hashes: URL var allowlist: URL var staged = false var message: URL? var artifacts: [URL] = [] var reportAllowed = false var json = false var names: URL var context: URL?
init(_ arguments: [String], root: URL, generate: Bool) throws { hashes = root.appendingPathComponent("Scripts/name-hashes.json") allowlist = root.appendingPathComponent("Scripts/name-allowlist.json") names = NamePaths.expanded( ProcessInfo.processInfo.environment["PARCEL_NAMES_FILE"] ?? "~/.config/parcel-dev/blocked-names.txt") var index = 0 while index < arguments.count { let argument = arguments[index] index += 1 func path() throws -> URL { guard index < arguments.count else { throw DevError("Missing value for \(argument)") } defer { index += 1 } return NamePaths.expanded(arguments[index]) } switch argument { case "--hashes": hashes = try path() case "--allowlist" where !generate: allowlist = try path() case "--staged" where !generate: staged = true case "--commit-msg" where !generate: message = try path() case "--artifact" where !generate: artifacts.append(try path()) case "--report-allowed" where !generate: reportAllowed = true case "--json" where !generate: json = true case "--names-file" where generate: names = try path() case "--context-file" where generate: context = try path() default: throw DevError("Unknown name guard argument: \(argument)") } } }}
enum NameTools { static func run(_ arguments: [String]) throws -> Int32 { guard let command = arguments.first, ["check", "generate"].contains(command) else { throw DevError("Usage: parcel-dev name-guard check|generate [OPTIONS]") } let root = try NamePaths.canonical( URL( fileURLWithPath: String( decoding: try DevProcess.checked("git", ["rev-parse", "--show-toplevel"]), as: UTF8.self ).trimmingCharacters(in: .whitespacesAndNewlines) )) let options = try NameOptions(Array(arguments.dropFirst()), root: root, generate: command == "generate") if command == "generate" { try generate(options, root: root); return 0 } return try check(options, root: root) }
static func privateNames(_ path: URL, root: URL) throws -> Set<String> { let resolved = try NamePaths.canonical(path) guard resolved != root, !resolved.path.hasPrefix(root.path + "/") else { throw DevError("Private input must be outside the repository") } var names: Set<String> = [] for (index, line) in try String(contentsOf: resolved, encoding: .utf8).components(separatedBy: .newlines) .enumerated() { if line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { continue } let words = NameScanner.words(Array(line.unicodeScalars)) guard (1...2).contains(words.count), try NameRegex.matches("\\s*[\\p{L}\\p{N}]+(?:\\s+[\\p{L}\\p{N}]+)?\\s*", line) else { throw DevError("Private input line \(index + 1) must contain one token or a token pair") } let name = words.map { $0.value.lowercased() }.joined(separator: " ") guard names.insert(name).inserted else { throw DevError("Duplicate private input at line \(index + 1)") } } guard !names.isEmpty else { throw DevError("Private input must not be empty") } return names }
private static func generate(_ options: NameOptions, root: URL) throws { let previous: NamePolicy? if FileManager.default.fileExists(atPath: options.hashes.path) { previous = try NamePolicy(Data(contentsOf: options.hashes)) } else { previous = nil } let salt: String if let previous { salt = previous.salt } else { var bytes = [UInt8](repeating: 0, count: 16) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw DevError("Could not generate policy salt") } salt = bytes.map { String(format: "%02x", $0) }.joined() } let names = try privateNames(options.names, root: root) let template: DevJSON = .object([ "version": .number(1), "salt": .string(salt), "always": .array([.string(String(repeating: "0", count: 64))]), "contextual": .array([]), ]) let policy = try NamePolicy(template.encoded()) let hashes = Set(names.map(policy.digest)) let contextual: Set<String> if let context = options.context { let contextNames = try privateNames(context, root: root) guard contextNames.isSubset(of: names) else { throw DevError("Context-only input must be a subset of the private names") } contextual = Set(contextNames.map(policy.digest)) } else { contextual = hashes.intersection(previous?.contextual ?? []) } let document: DevJSON = .object([ "version": .number(1), "salt": .string(salt), "always": .array(hashes.subtracting(contextual).sorted().map(DevJSON.string)), "contextual": .array(contextual.sorted().map(DevJSON.string)), ]) var data = try document.encoded() data.append(10) try data.write(to: options.hashes) print("Wrote \(hashes.count) salted hashes (\(contextual.count) context-only).") }
private static func check(_ options: NameOptions, root: URL) throws -> Int32 { guard !options.staged || options.artifacts.isEmpty else { throw DevError("--artifact requires a full check; it cannot be combined with --staged") } let index = options.staged ? try NameIndex(root: root, policies: [options.hashes, options.allowlist]) : nil func read(_ path: URL) throws -> Data { if let index { try index.read(path) } else { try Data(contentsOf: path) } } let scanner = try NameScanner( policy: NamePolicy(read(options.hashes)), allowances: NameAllowances(read(options.allowlist))) let files: [(String, Data)] if let index { files = index.files.sorted(by: { $0.key < $1.key }).map { ($0.key, $0.value) } } else { files = try NameGit.entries(root: root).map { entry in guard entry.mode != "160000" else { throw DevError("Submodule contents cannot be checked: \(entry.path)") } let path = root.appendingPathComponent(entry.path) let data: Data if entry.mode == "120000" { data = Data(try FileManager.default.destinationOfSymbolicLink(atPath: path.path).utf8) } else { data = try Data(contentsOf: path) } return (entry.path, data) } } for (path, data) in files { try scanner.scan("path", source: path, text: path) if data.contains(0) { let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("parcel-name-\(UUID())") try data.write(to: temporary, options: .withoutOverwriting) do { try scanner.binary("content", source: path, path: temporary) try FileManager.default.removeItem(at: temporary) } catch { do { try FileManager.default.removeItem(at: temporary) } catch { FileHandle.standardError.write(Data("Could not remove name snapshot: \(error)\n".utf8)) } throw error } } else { try scanner.scan("content", source: path, text: String(decoding: data, as: UTF8.self)) } } if !options.staged { let head = try DevProcess.run("git", ["rev-parse", "--verify", "--quiet", "HEAD"], directory: root) if head.status != 1 || !head.stderr.isEmpty { guard head.status == 0 else { throw DevError("Could not resolve Git HEAD") } let log = String( decoding: try NameGit.run(["log", "--all", "--format=%H%x00%B%x00"], root: root), as: UTF8.self ).components(separatedBy: "\0") for index in stride(from: 0, to: log.count - 1, by: 2) { try scanner.scan( "commit", source: log[index].trimmingCharacters(in: .whitespacesAndNewlines), text: log[index + 1]) } } } if let message = options.message { try scanner.scan("commit", source: "proposed-message", text: String(contentsOf: message, encoding: .utf8)) } var artifacts = options.staged ? Set<URL>() : try NameArtifacts.files(root: root) for path in options.artifacts { let resolved = try NamePaths.canonical(path) let properties = try resolved.resourceValues(forKeys: [.isRegularFileKey]) guard properties.isRegularFile == true else { throw DevError("Artifact must be a file: \(path.path)") } artifacts.insert(resolved) } for path in artifacts.sorted(by: { $0.path < $1.path }) { let source = try NameIndex.relative(path, root: root) ?? path.path try scanner.scan("path", source: source, text: source) try scanner.binary("artifact", source: NameArtifacts.source(source), path: path, checkout: root.path) } if options.json { struct Report: Encodable { let violations: [NameHit]; let allowed: [NameHit]; let artifacts: Int } let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] FileHandle.standardOutput.write( try encoder.encode( Report(violations: scanner.hits, allowed: scanner.allowed, artifacts: scanner.artifacts))) print("") } else { for hit in scanner.hits { FileHandle.standardError.write( Data( "\(hit.source):\(hit.line):\(hit.column): blocked name (\(hit.scope), \(hit.tokenHash.prefix(12)))\n" .utf8)) } if options.reportAllowed { for hit in scanner.allowed { print( "\(hit.source):\(hit.line):\(hit.column): allowed (\(hit.reason ?? ""), \(hit.tokenHash.prefix(12)))" ) } } if scanner.hits.isEmpty { print("Name check passed (\(scanner.artifacts) artifacts, \(scanner.allowed.count) allowed hits).") } else { FileHandle.standardError.write( Data( "Describe the idea instead. Review exact-context exceptions in Scripts/name-allowlist.json.\n" .utf8)) } } return scanner.hits.isEmpty ? 0 : 1 }}