Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / PackLib / XcodePacker.swift

XcodePacker.swift292 lines · 12.6 KiBRaw
1import Foundation
2import XcodeProjects
3
4public struct XcodePacker {
5 public var plan: Plan
6
7 public init(plan: Plan) {
8 self.plan = plan
9 }
10
11 // swiftlint:disable:next function_body_length
12 public func createProject(
13 at root: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
14 ) async throws -> URL {
15 let xtoolDir = root.appendingPathComponent("xtool", isDirectory: true)
16 let projectDir = xtoolDir.appendingPathComponent(".xtool-tmp", isDirectory: true)
17 try? FileManager.default.removeItem(at: projectDir)
18 try FileManager.default.createDirectory(at: projectDir, withIntermediateDirectories: true)
19
20 let fromProjectToRoot = "../.."
21
22 let emptyText = Data("// leave this file empty".utf8)
23 let products = plan.allProducts
24 let targetIDs = products.map {
25 XCSchema.ObjectID("xtool:\($0.product)")
26 }
27 let sourcePhase = XCSchema.BuildPhase.sources(.init(objectID: nil, name: nil))
28 let frameworksPhase = XCSchema.BuildPhase.frameworks(.init(objectID: nil, name: nil))
29
30 var groups: [XCSchema.Reference] = []
31 var productFiles: [XCSchema.Reference] = []
32 var targets: [XCSchema.Target] = []
33
34 for (index, product) in products.enumerated() {
35 let productDir = projectDir.appendingPathComponent(product.product, isDirectory: true)
36 try FileManager.default.createDirectory(at: productDir, withIntermediateDirectories: true)
37 try emptyText.write(to: productDir.appendingPathComponent("empty.c"))
38
39 var plist = product.infoPlist
40 let families = (plist.removeValue(forKey: "UIDeviceFamily") as? [Int]) ?? [1, 2]
41 plist["CFBundleExecutable"] = product.targetName
42 plist["CFBundleName"] = product.targetName
43 plist["CFBundleDisplayName"] = product.product
44 if let iconPath = product.iconPath {
45 plist["CFBundleIconFile"] = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent
46 }
47 let encodedPlist = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
48 try encodedPlist.write(to: productDir.appendingPathComponent("Info.plist"))
49
50 var buildSettings: [String: XCSchema.BuildSetting] = [
51 "PRODUCT_BUNDLE_IDENTIFIER": .string(product.bundleID),
52 "PRODUCT_NAME": .string(product.targetName),
53 "TARGETED_DEVICE_FAMILY": .string(families.map(String.init).joined(separator: ",")),
54 "IPHONEOS_DEPLOYMENT_TARGET": .string(product.deploymentTarget),
55 "INFOPLIST_FILE": .string("\(product.product)/Info.plist"),
56 "LD_RUNPATH_SEARCH_PATHS": .array(["$(inherited)", "@executable_path/Frameworks"]),
57 ]
58 if product.type == .appExtension {
59 buildSettings["APPLICATION_EXTENSION_API_ONLY"] = .string("YES")
60 buildSettings["LD_RUNPATH_SEARCH_PATHS"] = .array([
61 "$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks",
62 ])
63 }
64 if let entitlementsPath = product.entitlementsPath {
65 let path = (entitlementsPath as NSString).isAbsolutePath
66 ? entitlementsPath
67 : (fromProjectToRoot as NSString).appendingPathComponent(entitlementsPath)
68 buildSettings["CODE_SIGN_ENTITLEMENTS"] = .string(path)
69 }
70
71 let source = XCSchema.FileReference(
72 objectID: nil,
73 path: "empty.c",
74 explicitFileType: nil,
75 expectedSignature: nil,
76 textEncoding: nil,
77 lineEnding: nil,
78 includeInIndex: nil,
79 buildFiles: [.init(
80 objectID: nil,
81 buildPhase: .named(
82 target: .init(targetName: product.targetName),
83 kind: .sources,
84 name: nil
85 ),
86 properties: buildFileProperties(),
87 )],
88 )
89 let info = XCSchema.FileReference(
90 objectID: nil,
91 path: "Info.plist",
92 explicitFileType: nil,
93 expectedSignature: nil,
94 textEncoding: nil,
95 lineEnding: nil,
96 includeInIndex: nil,
97 buildFiles: [],
98 )
99 let resources = try resourceReferences(for: product, at: root)
100 groups.append(.group(.init(
101 objectID: nil,
102 name: product.product,
103 path: try .init(base: .group, path: product.product),
104 includeInIndex: nil,
105 children: [.fileReference(source), .fileReference(info)] + resources,
106 )))
107
108 let productFilename = "\(product.targetName).\(product.type == .application ? "app" : "appex")"
109 let productFile = XCSchema.FileReference(
110 objectID: nil,
111 path: try .init(base: .buildProducts, path: productFilename),
112 explicitFileType: .init(fileTypeID: product.type == .application ? "wrapper.application" : "wrapper.app-extension"),
113 expectedSignature: nil,
114 textEncoding: nil,
115 lineEnding: nil,
116 includeInIndex: false,
117 buildFiles: index == 0 ? [] : [.init(
118 objectID: nil,
119 buildPhase: .named(
120 target: .init(targetName: plan.app.targetName),
121 kind: .copy,
122 name: "Embed App Extensions",
123 ),
124 properties: buildFileProperties(removeHeadersOnCopy: true),
125 )],
126 )
127 productFiles.append(.fileReference(productFile))
128
129 let packageProduct = XCSchema.SwiftPackageProductReference(
130 objectID: nil,
131 package: nil,
132 productName: product.product,
133 productType: .other,
134 )
135 let packageMember = XCSchema.SwiftPackageProductTargetMember(
136 packageProduct: packageProduct,
137 buildFile: .init(
138 objectID: nil,
139 buildPhase: .named(kind: .frameworks, name: nil),
140 properties: buildFileProperties(),
141 ),
142 )
143 var phases = [sourcePhase, frameworksPhase]
144 if !resources.isEmpty {
145 phases.append(.copy(.init(
146 objectID: nil,
147 name: "Copy Root Resources",
148 bundleBasePath: .resourcesDir,
149 relativePath: "",
150 scope: .always,
151 )))
152 }
153 if index == 0 && !plan.extensions.isEmpty {
154 phases.append(.copy(.init(
155 objectID: nil,
156 name: "Embed App Extensions",
157 bundleBasePath: .plugInsDir,
158 relativePath: "",
159 scope: .always,
160 )))
161 }
162 let dependencies: [XCSchema.TargetDependency] = index == 0
163 ? plan.extensions.map {
164 .localTarget(XCSchema.LocalTargetReference(targetName: $0.targetName), [])
165 }
166 : []
167 targets.append(.native(XCSchema.CommonTargetProperties(
168 name: product.targetName,
169 objectID: targetIDs[index],
170 configurationListDebugID: nil,
171 dependencies: dependencies,
172 buildPhases: phases,
173 buildRules: [],
174 specializedConfigurations: [],
175 buildSettings: buildSettings,
176 product: .namePath(.init(components: [.child("Products"), .child(productFilename)])),
177 productTypeID: XCSchema.ProductTypeID(
178 abbreviatedRepresentation: product.type == .application
179 ? "application"
180 : "app-extension"
181 ),
182 testHostTarget: nil,
183 legacyProvisioningStyle: nil,
184 legacyTeamID: nil,
185 lastSwiftUpdateCheck: nil,
186 lastSwiftMigration: nil,
187 packageProductTargetMembers: [packageMember],
188 )))
189 }
190
191 let schema = XCSchema.Project(
192 objectID: nil,
193 rootGroupDebugID: nil,
194 configurationListDebugID: nil,
195 topLevelReferences: groups + [
196 .group(XCSchema.Group(
197 objectID: nil,
198 name: "Products",
199 path: "",
200 includeInIndex: nil,
201 children: productFiles,
202 ))
203 ],
204 packages: [.init(location: .local(.init(path: fromProjectToRoot)), traits: [])],
205 configurations: ["Debug", "Release"].map {
206 .init(name: .init(name: $0), file: nil, objectID: nil)
207 },
208 buildSettings: ["SDKROOT": .string("iphoneos")],
209 defaultConfigurationName: .init(name: "Debug"),
210 targets: targets,
211 localizationInfo: .init(development: .init(languageID: "en"), supported: []),
212 requiredCapabilities: [],
213 buildIndependentTargetsInParallel: true,
214 lastUpgradeCheck: nil,
215 lastSwiftUpdateCheck: nil,
216 lastSwiftMigration: nil,
217 organizationName: nil,
218 classPrefix: nil,
219 productsGroup: .namePath(.init(components: [.child("Products")])),
220 importedProducts: [],
221 )
222
223 let projectURL = projectDir.appending(path: "\(plan.app.product).xcodeproj")
224 let project = XcodeProject(project: schema, url: projectURL)
225 try project.write()
226
227 let workspaceURL = xtoolDir.appending(path: "\(plan.app.product).xcworkspace")
228 let workspace = XcodeWorkspace(children: [
229 .file(XcodeWorkspace.Location(base: .container, path: "..")),
230 .file(XcodeWorkspace.Location(base: .group, path: ".xtool-tmp/\(projectURL.lastPathComponent)"))
231 ], url: workspaceURL)
232 try workspace.write()
233 return workspaceURL
234 }
235
236 private func resourceReferences(for product: Plan.Product, at root: URL) throws -> [XCSchema.Reference] {
237 var paths = product.resources.compactMap { resource -> String? in
238 guard case .root(let source) = resource else { return nil }
239 return source
240 }
241 if let iconPath = product.iconPath {
242 paths.append(iconPath)
243 }
244
245 var visited: Set<String> = []
246 return try paths.compactMap { path in
247 let url = URL(fileURLWithPath: path, relativeTo: root).standardizedFileURL
248 guard visited.insert(url.path).inserted else { return nil }
249 let isAbsolute = (path as NSString).isAbsolutePath
250 let referencePath = isAbsolute ? path : ("../.." as NSString).appendingPathComponent(path)
251 var isDirectory: ObjCBool = false
252 _ = FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)
253
254 return .fileReference(.init(
255 objectID: nil,
256 path: try .init(base: isAbsolute ? .absolute : .project, path: referencePath),
257 explicitFileType: isDirectory.boolValue ? .init(fileTypeID: "folder") : nil,
258 expectedSignature: nil,
259 textEncoding: nil,
260 lineEnding: nil,
261 includeInIndex: nil,
262 buildFiles: [.init(
263 objectID: nil,
264 buildPhase: .named(
265 target: .init(targetName: product.targetName),
266 kind: .copy,
267 name: "Copy Root Resources",
268 ),
269 properties: buildFileProperties(),
270 )],
271 ))
272 }
273 }
274
275 private func buildFileProperties(removeHeadersOnCopy: Bool = false) -> XCSchema.BuildFileProperties {
276 XCSchema.BuildFileProperties(
277 platformFilters: [],
278 additionalBuildFlags: nil,
279 assetTags: [],
280 attributes: XCSchema.BuildFileAttributes(
281 headerRole: nil,
282 machInterfaceGeneration: nil,
283 isWeak: false,
284 codeSignOnCopy: false,
285 codeGeneration: .default,
286 headerPreservation: removeHeadersOnCopy ? .removeOnCopy : .keep,
287 decompress: false,
288 codeGenerationVisibility: nil,
289 ),
290 )
291 }
292}