-
Notifications
You must be signed in to change notification settings - Fork 784
Expand file tree
/
Copy pathApp.swift
More file actions
219 lines (173 loc) · 8.5 KB
/
App.swift
File metadata and controls
219 lines (173 loc) · 8.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//
// App.swift
// rswift
//
// Created by Tom Lokhorst on 2021-04-18.
//
import ArgumentParser
import Foundation
import RswiftParsers
import XcodeEdit
@main
struct App: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "rswift",
abstract: "Generate static references for autocompleted resources like images, fonts and localized strings in Swift projects",
version: Config.version,
subcommands: [Generate.self, ModifyXcodePackages.self]
)
}
enum InputType: String, ExpressibleByArgument {
case xcodeproj = "xcodeproj"
case inputFiles = "input-files"
}
struct GlobalOptions: ParsableArguments {
@Option(help: "The type of input for generation")
var inputType: InputType = .xcodeproj
@Option(help: "Only run specified generators, options: \(generatorsString)", transform: parseGenerators)
var generators: [ResourceType] = []
@Flag(help: "Don't generate main `R` let")
var omitMainLet = false
@Option(name: .customLong("import", withSingleDash: false), help: "Add extra modules as import in the generated file")
var imports: [String] = []
@Option(help: "The access level [public|internal] to use for the generated R-file")
var accessLevel: AccessLevel = .internalLevel
@Option(help: "Path to pattern file that describes files that should be ignored")
var rswiftignore = ".rswiftignore"
@Option(help: "Paths of files for which resources should be generated")
var inputFiles: [String] = []
@Option(help: "Source of default bundle to use")
var bundleSource: BundleSource = .finder
@Option(help: "Development region for provided inputFiles")
var developmentRegion: String?
// MARK: Project specific - Environment variable overrides
@Option(help: "Override environment variable \(EnvironmentKeys.targetName)")
var target: String?
}
private let generatorsString = ResourceType.allCases.map(\.rawValue).joined(separator: ", ")
private func parseGenerators(_ str: String) -> [ResourceType] {
str.components(separatedBy: ",").map { ResourceType(rawValue: $0)! }
}
extension App {
struct Generate: ParsableCommand {
static let configuration = CommandConfiguration(abstract: "Generates R.generated.swift file")
@OptionGroup
var globals: GlobalOptions
@Option(help: "Override environment variable \(EnvironmentKeys.productFilePath)")
var xcodeproj: String?
@Argument(help: "Output path for the generated file")
var outputPath: String
mutating func run() throws {
let processInfo = ProcessInfo.processInfo
let productModuleName = processInfo.environment[EnvironmentKeys.productModuleName]
let infoPlistFile = processInfo.environment[EnvironmentKeys.infoPlistFile]
let codeSignEntitlements = processInfo.environment[EnvironmentKeys.codeSignEntitlements]
// If no environment is provided, we're not running inside Xcode, fallback to names
let sourceTreeURLs = SourceTreeURLs(
builtProductsDirURL: URL(fileURLWithPath: processInfo.environment[EnvironmentKeys.builtProductsDir] ?? EnvironmentKeys.builtProductsDir),
developerDirURL: URL(fileURLWithPath: processInfo.environment[EnvironmentKeys.developerDir] ?? EnvironmentKeys.developerDir),
sourceRootURL: URL(fileURLWithPath: processInfo.environment[EnvironmentKeys.sourceRoot] ?? "."),
sdkRootURL: URL(fileURLWithPath: processInfo.environment[EnvironmentKeys.sdkRoot] ?? EnvironmentKeys.sdkRoot),
platformURL: URL(fileURLWithPath: processInfo.environment[EnvironmentKeys.platformDir] ?? EnvironmentKeys.platformDir)
)
let outputURL = URL(fileURLWithPath: outputPath)
let rswiftIgnoreURL = sourceTreeURLs.sourceRootURL
.appendingPathComponent(globals.rswiftignore, isDirectory: false)
let core = RswiftCore(
outputURL: outputURL,
generators: globals.generators.isEmpty ? ResourceType.allCases : globals.generators,
accessLevel: globals.accessLevel,
bundleSource: globals.bundleSource,
importModules: globals.imports,
productModuleName: productModuleName,
infoPlistFile: infoPlistFile.map(URL.init(fileURLWithPath:)),
codeSignEntitlements: codeSignEntitlements.map(URL.init(fileURLWithPath:)),
omitMainLet: globals.omitMainLet,
rswiftIgnoreURL: rswiftIgnoreURL,
sourceTreeURLs: sourceTreeURLs
)
do {
switch globals.inputType {
case .xcodeproj:
let xcodeprojPath = try xcodeproj ?? ProcessInfo.processInfo
.environmentVariable(name: EnvironmentKeys.productFilePath)
let xcodeprojURL = URL(fileURLWithPath: xcodeprojPath)
let targetName = try getTargetName(xcodeprojURL: xcodeprojURL)
try core.generateFromXcodeproj(url: xcodeprojURL, targetName: targetName)
case .inputFiles:
try core.generateFromFiles(
inputFileURLs: globals.inputFiles.map(URL.init(fileURLWithPath:)),
developmentRegion: globals.developmentRegion
)
}
} catch let error as ResourceParsingError {
throw ValidationError(error.description)
}
}
func getTargetName(xcodeprojURL: URL) throws -> String {
if let targetName = globals.target ?? ProcessInfo.processInfo
.environment[EnvironmentKeys.targetName] {
return targetName
}
do {
let xcodeproj = try Xcodeproj(url: xcodeprojURL, warning: { _ in })
let targets = xcodeproj.allTargets
if let target = targets.first, targets.count == 1 {
return target.name
}
if targets.count > 0 {
let lines = [
"Missing argument --target",
"Available targets:"
] + targets.map { "- \($0.name)" }
throw ValidationError(lines.joined(separator: "\n"))
}
throw ValidationError("Missing argument --target")
} catch {
throw ValidationError("Missing argument --target")
}
}
}
}
extension App {
struct ModifyXcodePackages: ParsableCommand {
static let configuration = CommandConfiguration(abstract: "Modifies Xcode project to fix package reference for plugins")
@Option(help: "Path to xcodeproj file")
var xcodeproj: String
@Option(help: "Targets for which to remove package reference")
var target: [String] = []
mutating func run() throws {
let url = URL(fileURLWithPath: xcodeproj)
let file = try XCProjectFile(xcodeprojURL: url, ignoreReferenceErrors: true)
for target in file.project.targets.compactMap(\.value) {
guard self.target.contains(target.name) else { continue }
for product in target.dependencies.compactMap(\.value?.productRef?.value) {
let plugins = ["plugin:RswiftGenerateInternalResources", "plugin:RswiftGeneratePublicResources"]
if let name = product.productName, plugins.contains(name) {
product.removePackage()
}
}
}
try file.write(to: url)
}
}
}
struct EnvironmentKeys {
static let action = "ACTION"
static let targetName = "TARGET_NAME"
static let infoPlistFile = "INFOPLIST_FILE"
static let productFilePath = "PROJECT_FILE_PATH"
static let productModuleName = "PRODUCT_MODULE_NAME"
static let codeSignEntitlements = "CODE_SIGN_ENTITLEMENTS"
static let builtProductsDir = SourceTreeFolder.buildProductsDir.rawValue
static let developerDir = SourceTreeFolder.developerDir.rawValue
static let platformDir = SourceTreeFolder.platformDir.rawValue
static let sdkRoot = SourceTreeFolder.sdkRoot.rawValue
static let sourceRoot = SourceTreeFolder.sourceRoot.rawValue
}
extension ProcessInfo {
func environmentVariable(name: String) throws -> String {
guard let value = self.environment[name] else { throw ValidationError("Missing argument \(name)") }
return value
}
}