import Foundation indirect enum WorkflowValue: Equatable, Sendable { case scalar(String) case mapping([String: WorkflowValue]) case sequence([WorkflowValue]) var text: String? { guard case .scalar(let value) = self else { return nil } return value } } enum WorkflowTools { static func run(_ command: String, _ args: [String]) throws { guard command == "check-workflows", !args.isEmpty else { throw DevError("Usage: parcel-dev check-workflows FILE...") } for path in args { _ = try load(URL(fileURLWithPath: path)) } } static func load(_ path: URL) throws -> WorkflowValue { let data = try Data(contentsOf: path) guard let source = String(data: data, encoding: .utf8) else { throw DevError("Invalid UTF-8 workflow: \(path.path)") } return try WorkflowParser(source: source, path: path.path).parse() } static func parse(_ source: String, path: String = "workflow.yml") throws -> WorkflowValue { try WorkflowParser(source: source, path: path).parse() } } private final class WorkflowParser { struct Line { let raw: String let number: Int var indent: Int { raw.prefix(while: { $0 == " " }).count } var content: String { String(raw.dropFirst(indent)) } } let path: String let lines: [Line] var index = 0 var anchors: Set = [] init(source: String, path: String) { self.path = path self.lines = source.components(separatedBy: .newlines).enumerated().map { Line(raw: $0.element, number: $0.offset + 1) } } func error(_ message: String, line: Int) -> DevError { DevError("\(message): \(path):\(line)") } func parse() throws -> WorkflowValue { try skipBlank() if index < lines.count, lines[index].content == "---" { index += 1; try skipBlank() } guard index < lines.count else { throw error("Empty workflow", line: 1) } guard lines[index].indent == 0 else { throw error("Unexpected workflow indentation", line: lines[index].number) } let result = try block(indent: 0) try skipBlank() if index < lines.count, lines[index].content == "..." { index += 1; try skipBlank() } guard index == lines.count else { throw error("Multiple documents or malformed workflow YAML", line: lines[index].number) } guard case .mapping = result else { throw error("Workflow must be a mapping", line: 1) } return result } func skipBlank() throws { while index < lines.count { let line = lines[index] if line.raw.prefix(while: { $0.isWhitespace }).contains("\t") { throw error("Tabs are not allowed in workflow indentation", line: line.number) } let content = line.content.trimmingCharacters(in: .whitespaces) if content.isEmpty || content.hasPrefix("#") { index += 1 } else { break } } } func block(indent: Int) throws -> WorkflowValue { try skipBlank() guard index < lines.count else { return .scalar("") } let line = lines[index] guard line.indent == indent else { throw error("Unexpected workflow indentation", line: line.number) } let content = stripComment(line.content) if content == "-" || content.hasPrefix("- ") { return try sequence(indent: indent) } if mappingColon(content) != nil || content.hasPrefix("? ") { return try mapping(indent: indent) } index += 1 return try inline(content, line: line.number) } func sequence(indent: Int) throws -> WorkflowValue { var result: [WorkflowValue] = [] while true { try skipBlank() guard index < lines.count, lines[index].indent >= indent else { break } let line = lines[index] guard line.indent == indent else { throw error("Unexpected workflow indentation", line: line.number) } let content = stripComment(line.content) guard content == "-" || content.hasPrefix("- ") else { break } let rest = String(content.dropFirst()).trimmingCharacters(in: .whitespaces) index += 1 if mappingColon(rest) != nil || rest.hasPrefix("? ") { result.append(try mapping(indent: indent + 2, first: (rest, line.number))) } else { result.append(try value(rest, parentIndent: indent, line: line.number)) } } return .sequence(result) } func mapping(indent: Int, first: (String, Int)? = nil) throws -> WorkflowValue { var result: [String: WorkflowValue] = [:] var initial = first while true { let content: String let number: Int if let pair = initial { (content, number) = pair initial = nil } else { try skipBlank() guard index < lines.count, lines[index].indent >= indent else { break } let line = lines[index] guard line.indent == indent else { throw error("Unexpected workflow indentation", line: line.number) } if line.content == "---" || line.content == "..." { break } content = stripComment(line.content) number = line.number index += 1 } let keySource: String let valueSource: String if content.hasPrefix("? ") { keySource = String(content.dropFirst(2)) try skipBlank() guard index < lines.count, lines[index].indent == indent, lines[index].content.hasPrefix(":") else { throw error("Malformed explicit workflow key", line: number) } valueSource = String(stripComment(lines[index].content).dropFirst()).trimmingCharacters( in: .whitespaces) index += 1 } else { guard let colon = mappingColon(content) else { throw error("Malformed workflow mapping", line: number) } keySource = String(content[.. WorkflowValue { let decorated = try decorations(source, line: line) if decorated.isEmpty { try skipBlank() if index < lines.count, lines[index].indent > parentIndent { return try block(indent: lines[index].indent) } return .scalar("") } if decorated.hasPrefix("|") || decorated.hasPrefix(">") { return try blockScalar(decorated, parentIndent: parentIndent, line: line) } var complete = decorated if decorated.hasPrefix("[") || decorated.hasPrefix("{") { while !flowComplete(complete), index < lines.count { complete += "\n" + stripComment(lines[index].content) index += 1 } } return try inline(complete, line: line) } func blockScalar(_ header: String, parentIndent: Int, line: Int) throws -> WorkflowValue { let suffix = String(header.dropFirst()) guard suffix.count <= 2, suffix.allSatisfy({ $0 == "+" || $0 == "-" || ("123456789".contains($0)) }), suffix.filter({ $0 == "+" || $0 == "-" }).count <= 1, suffix.filter({ $0.isNumber }).count <= 1 else { throw error("Malformed workflow block scalar", line: line) } let explicit = suffix.first(where: { $0.isNumber }).flatMap { $0.wholeNumberValue }.map { parentIndent + $0 } var cursor = index while cursor < lines.count, lines[cursor].raw.trimmingCharacters(in: .whitespaces).isEmpty { cursor += 1 } let indent = explicit ?? (cursor < lines.count ? lines[cursor].indent : parentIndent + 1) var chunks: [String] = [] while index < lines.count { let next = lines[index] let blank = next.raw.trimmingCharacters(in: .whitespaces).isEmpty if !blank && next.indent <= parentIndent { break } if !blank && next.indent < indent { throw error("Malformed workflow block indentation", line: next.number) } chunks.append(blank ? "" : String(next.raw.dropFirst(indent))) index += 1 } var result = "" for offset in chunks.indices { result += chunks[offset] if offset + 1 < chunks.count { let fold = header.hasPrefix(">") && !chunks[offset].isEmpty && !chunks[offset + 1].isEmpty && !chunks[offset].hasPrefix(" ") && !chunks[offset + 1].hasPrefix(" ") result += fold ? " " : "\n" } } if suffix.contains("-") { result = result.trimmingCharacters(in: .newlines) } else if !suffix.contains("+") { result = result.trimmingCharacters(in: .newlines) + "\n" } else { result += "\n" } return .scalar(result) } func decorations(_ source: String, line: Int) throws -> String { var value = source.trimmingCharacters(in: .whitespacesAndNewlines) while value.hasPrefix("!") || value.hasPrefix("&") { let token = String(value.prefix(while: { !$0.isWhitespace })) if token.hasPrefix("!") { let allowed = ["str", "bool", "int", "float", "null", "map", "seq"] guard allowed.contains(where: { token == "!!" + $0 || token == "!" }) else { throw error("Unsupported workflow YAML tag", line: line) } } else { guard token.count > 1, !token.contains(where: { "[]{},".contains($0) }) else { throw error("Malformed workflow anchor", line: line) } guard anchors.insert(token).inserted else { throw error("Duplicate workflow anchor", line: line) } } value = String(value.dropFirst(token.count)).trimmingCharacters(in: .whitespacesAndNewlines) } if value.hasPrefix("*") { throw error("Workflow aliases are not allowed", line: line) } return value } func inline(_ source: String, line: Int) throws -> WorkflowValue { let value = try decorations(source, line: line) var reader = WorkflowInlineParser(source: value, owner: self, line: line) let result = try reader.readValue() reader.skipSpace() guard reader.finished else { throw error("Malformed workflow YAML scalar or collection", line: line) } return result } func validate(_ key: String, value: WorkflowValue, line: Int) throws { if key == "uses" { guard let action = value.text, action.hasPrefix("./") || action.wholeMatch(of: /[A-Za-z0-9_.-]+\/[A-Za-z0-9_.\/-]+@[a-f0-9]{40}/) != nil else { throw error("Unpinned uses (use a full commit SHA)", line: line) } } else if key == "runs-on" { guard let runner = value.text, runner.wholeMatch(of: /(?:macos|ubuntu|windows)-(?:latest|[0-9]+(?:\.[0-9]+)?)(?:-arm)?/) != nil else { throw error("GitHub-hosted runners only", line: line) } } } func mappingColon(_ source: String) -> String.Index? { var quote: Character? var escaped = false var depth = 0 for offset in source.indices { let character = source[offset] if escaped { escaped = false; continue } if character == "\\" && quote == "\"" { escaped = true; continue } if let current = quote { if character == current { quote = nil } continue } if character == "\"" || character == "'" { quote = character } else if character == "[" || character == "{" { depth += 1 } else if character == "]" || character == "}" { depth -= 1 } else if character == ":" && depth == 0 { let next = source.index(after: offset) if next == source.endIndex || source[next].isWhitespace { return offset } } } return nil } func stripComment(_ source: String) -> String { var quote: Character? var escaped = false for offset in source.indices { let character = source[offset] if escaped { escaped = false; continue } if character == "\\" && quote == "\"" { escaped = true; continue } if let current = quote { if character == current { quote = nil } } else if character == "\"" || character == "'" { quote = character } else if character == "#" && (offset == source.startIndex || source[source.index(before: offset)].isWhitespace) { return String(source[.. Bool { var quote: Character? var escaped = false var depth = 0 for character in source { if escaped { escaped = false; continue } if character == "\\" && quote == "\"" { escaped = true; continue } if let current = quote { if character == current { quote = nil } } else if character == "\"" || character == "'" { quote = character } else if character == "[" || character == "{" { depth += 1 } else if character == "]" || character == "}" { depth -= 1 } } return quote == nil && depth <= 0 } } private struct WorkflowInlineParser { let characters: [Character] let owner: WorkflowParser let line: Int var index = 0 var finished: Bool { index == characters.count } init(source: String, owner: WorkflowParser, line: Int) { characters = Array(source) self.owner = owner self.line = line } mutating func skipSpace() { while !finished && characters[index].isWhitespace { index += 1 } } mutating func readValue(flow: Bool = false, key: Bool = false) throws -> WorkflowValue { skipSpace() guard !finished else { return .scalar("") } let character = characters[index] if character == "*" { throw owner.error("Workflow aliases are not allowed", line: line) } if character == "!" || character == "&" { let start = index while !finished && !characters[index].isWhitespace && !"[]{},".contains(characters[index]) { index += 1 } _ = try owner.decorations(String(characters[start..%,]}".contains(character) else { throw owner.error("Malformed workflow scalar", line: line) } let start = index while !finished { let current = characters[index] if flow && ",]}".contains(current) { break } if current == ":" && (key || index + 1 == characters.count || characters[index + 1].isWhitespace) { break } if flow && (current == "[" || current == "{") { throw owner.error("Malformed workflow scalar", line: line) } index += 1 } let value = String(characters[start.. Bool { guard !finished, characters[index] == character else { return false } index += 1 return true } mutating func quoted() throws -> String { let quote = characters[index] index += 1 var result = "" while !finished { let character = characters[index] index += 1 if character == quote { if quote == "'" && consume("'") { result.append("'"); continue } return result } if quote == "\"" && character == "\\" { guard !finished else { break } let escape = characters[index] index += 1 let replacements: [Character: String] = [ "0": "\0", "a": "\u{7}", "b": "\u{8}", "t": "\t", "n": "\n", "v": "\u{B}", "f": "\u{C}", "r": "\r", "e": "\u{1B}", " ": " ", "\"": "\"", "/": "/", "\\": "\\", "N": "\u{85}", "_": "\u{A0}", "L": "\u{2028}", "P": "\u{2029}", ] if let replacement = replacements[escape] { result += replacement } else if escape == "x" || escape == "u" || escape == "U" { let count = escape == "x" ? 2 : escape == "u" ? 4 : 8 guard index + count <= characters.count, let number = UInt32(String(characters[index..