|
| 1 | +import Foundation |
| 2 | +import PackagePlugin |
| 3 | + |
| 4 | +/// Provides `protocol` decoding/encoding syntax generation. |
| 5 | +/// |
| 6 | +/// Creates build commands that produces syntax for `protocol`s |
| 7 | +/// that indicate dynamic decoding/encoding with `Codable` macro. |
| 8 | +@main |
| 9 | +struct MetaProtocolCodable: BuildToolPlugin { |
| 10 | + /// Fetches config data from file. |
| 11 | + /// |
| 12 | + /// The alphanumeric characters of file name must case-insensitively |
| 13 | + /// match `"metacodableconfig"`, and the data contained must be |
| 14 | + /// either `plist` or `json` format, i.e. `metacodable-config.json`, |
| 15 | + /// `metacodable_config.json`, `MetaCodableConfig.plist` are |
| 16 | + /// all valid names. |
| 17 | + /// |
| 18 | + /// - Parameter target: The target including plugin. |
| 19 | + /// - Returns: The config if provided, otherwise default config. |
| 20 | + func fetchConfig(for target: SourceModuleTarget) async throws -> Config { |
| 21 | + let fileManager = FileManager.default |
| 22 | + let directory = target.directory.string |
| 23 | + let contents = try fileManager.contentsOfDirectory(atPath: directory) |
| 24 | + let file = contents.first { file in |
| 25 | + let path = Path(file) |
| 26 | + let name = path.stem |
| 27 | + .components(separatedBy: .alphanumerics.inverted) |
| 28 | + .joined(separator: "") |
| 29 | + .lowercased() |
| 30 | + return name == "metacodableconfig" |
| 31 | + } |
| 32 | + guard let file else { return .init(scan: .target) } |
| 33 | + let path = if #available(macOS 13, *) { |
| 34 | + URL(filePath: target.directory.appending([file]).string) |
| 35 | + } else { |
| 36 | + URL(fileURLWithPath: target.directory.appending([file]).string) |
| 37 | + } |
| 38 | + let (conf, _) = try await URLSession.shared.data(from: path) |
| 39 | + let pConf = try? PropertyListDecoder().decode(Config.self, from: conf) |
| 40 | + let config = try pConf ?? JSONDecoder().decode(Config.self, from: conf) |
| 41 | + return config |
| 42 | + } |
| 43 | + |
| 44 | + /// Invoked by SwiftPM to create build commands for a particular target. |
| 45 | + /// |
| 46 | + /// Creates build commands that produces intermediate files scanning |
| 47 | + /// swift source files according to configuration. Final build command |
| 48 | + /// generates syntax aggregating all intermediate files. |
| 49 | + /// |
| 50 | + /// - Parameters: |
| 51 | + /// - context: The package and environmental inputs context. |
| 52 | + /// - target: The target including plugin. |
| 53 | + /// |
| 54 | + /// - Returns: The commands to be executed during build. |
| 55 | + func createBuildCommands( |
| 56 | + context: PluginContext, target: Target |
| 57 | + ) async throws -> [Command] { |
| 58 | + guard let target = target as? SourceModuleTarget else { return [] } |
| 59 | + let tool = try context.tool(named: "ProtocolGen") |
| 60 | + // Get Config |
| 61 | + let config = try await fetchConfig(for: target) |
| 62 | + let (allTargets, imports) = config.scanInput(for: target) |
| 63 | + // Setup folder |
| 64 | + let genFolder = context.pluginWorkDirectory.appending(["ProtocolGen"]) |
| 65 | + try FileManager.default.createDirectory( |
| 66 | + atPath: genFolder.string, withIntermediateDirectories: true |
| 67 | + ) |
| 68 | + |
| 69 | + // Create source scan commands |
| 70 | + var intermFiles: [Path] = [] |
| 71 | + var buildCommands = allTargets.flatMap { target in |
| 72 | + return target.sourceFiles(withSuffix: "swift").map { file in |
| 73 | + let moduleName = target.moduleName |
| 74 | + let fileName = file.path.stem |
| 75 | + let genFileName = "\(moduleName)-\(fileName)-gen.json" |
| 76 | + let genFile = genFolder.appending([genFileName]) |
| 77 | + intermFiles.append(genFile) |
| 78 | + return Command.buildCommand( |
| 79 | + displayName: """ |
| 80 | + Parse source file "\(fileName)" in module "\(moduleName)" |
| 81 | + """, |
| 82 | + executable: tool.path, |
| 83 | + arguments: [ |
| 84 | + "parse", |
| 85 | + file.path.string, |
| 86 | + "--output", |
| 87 | + genFile.string, |
| 88 | + ], |
| 89 | + inputFiles: [file.path], |
| 90 | + outputFiles: [genFile] |
| 91 | + ) |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + // Create syntax generation command |
| 96 | + let moduleName = target.moduleName |
| 97 | + let genFileName = "\(moduleName)+ProtocolHelperCoders.swift" |
| 98 | + let genPath = genFolder.appending(genFileName) |
| 99 | + var genArgs = ["generate", "--output", genPath.string] |
| 100 | + for `import` in imports { |
| 101 | + genArgs.append(contentsOf: ["--module", `import`]) |
| 102 | + } |
| 103 | + for file in intermFiles { |
| 104 | + genArgs.append(file.string) |
| 105 | + } |
| 106 | + buildCommands.append(.buildCommand( |
| 107 | + displayName: """ |
| 108 | + Generate protocol decoding/encoding syntax for "\(moduleName)" |
| 109 | + """, |
| 110 | + executable: tool.path, |
| 111 | + arguments: genArgs, |
| 112 | + inputFiles: intermFiles, |
| 113 | + outputFiles: [genPath] |
| 114 | + )) |
| 115 | + return buildCommands |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +extension Config { |
| 120 | + /// Returns targets to scan and import modules based on current |
| 121 | + /// configuration. |
| 122 | + /// |
| 123 | + /// Based on configuration, the targets for which source files need |
| 124 | + /// to be checked and the modules that will be imported in final syntax |
| 125 | + /// generated is returned. |
| 126 | + /// |
| 127 | + /// - Parameter target: The target including plugin. |
| 128 | + /// - Returns: The targets to scan and modules to import. |
| 129 | + func scanInput( |
| 130 | + for target: SourceModuleTarget |
| 131 | + ) -> (targets: [SourceModuleTarget], modules: [String]) { |
| 132 | + let allTargets: [SourceModuleTarget] |
| 133 | + let modules: [String] |
| 134 | + switch scan { |
| 135 | + case .target: |
| 136 | + allTargets = [target] |
| 137 | + modules = [] |
| 138 | + case .local: |
| 139 | + var targets = target.dependencies.compactMap { dependency in |
| 140 | + return switch dependency { |
| 141 | + case .target(let target): |
| 142 | + target.sourceModule |
| 143 | + default: |
| 144 | + nil |
| 145 | + } |
| 146 | + } |
| 147 | + modules = targets.map(\.moduleName) |
| 148 | + targets.append(target) |
| 149 | + allTargets = targets |
| 150 | + case .recursive: |
| 151 | + var targets = target.recursiveTargetDependencies.compactMap { |
| 152 | + return $0 as? SourceModuleTarget |
| 153 | + } |
| 154 | + modules = targets.map(\.moduleName) |
| 155 | + targets.append(target) |
| 156 | + allTargets = targets |
| 157 | + } |
| 158 | + return (allTargets, modules) |
| 159 | + } |
| 160 | +} |
0 commit comments