ZipBuilder.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import FirebaseManifest
  18. /// Misc. constants used in the build tool.
  19. struct Constants {
  20. /// Constants related to the Xcode project template.
  21. struct ProjectPath {
  22. // Required for building.
  23. static let infoPlist = "Info.plist"
  24. static let projectFile = "FrameworkMaker.xcodeproj"
  25. /// All required files for building the Zip file.
  26. static let requiredFilesForBuilding: [String] = [projectFile, infoPlist]
  27. // Required for distribution.
  28. static let readmeName = "README.md"
  29. // Required from the Firebase pod.
  30. static let firebaseHeader = "Firebase.h"
  31. static let modulemap = "module.modulemap"
  32. /// The dummy Firebase library for Carthage distribution.
  33. static let dummyFirebaseLib = "dummy_Firebase_lib"
  34. // Make the struct un-initializable.
  35. @available(*, unavailable)
  36. init() { fatalError() }
  37. }
  38. /// The text added to the README for a product if it contains Resources. The empty line at the end
  39. /// is intentional.
  40. static let resourcesRequiredText = """
  41. You'll also need to add the resources in the Resources
  42. directory into your target's main bundle.
  43. """
  44. // Make the struct un-initializable.
  45. @available(*, unavailable)
  46. init() { fatalError() }
  47. }
  48. /// A zip file builder. The zip file can be built with the `buildAndAssembleReleaseDir()` function.
  49. struct ZipBuilder {
  50. /// Artifacts from building and assembling the release directory.
  51. struct ReleaseArtifacts {
  52. /// The Firebase version.
  53. let firebaseVersion: String
  54. /// The directory that contains the properly assembled release artifacts.
  55. let zipDir: URL
  56. /// The directory that contains the properly assembled release artifacts for Carthage if building it.
  57. let carthageDir: URL?
  58. }
  59. /// Relevant paths in the filesystem to build the release directory.
  60. struct FilesystemPaths {
  61. // MARK: - Required Paths
  62. /// The root of the `firebase-ios-sdk` git repo.
  63. let repoDir: URL
  64. /// The path to the directory containing the blank xcodeproj and Info.plist for building source
  65. /// based frameworks. Generated based on the `repoDir`.
  66. var templateDir: URL {
  67. return type(of: self).templateDir(fromRepoDir: repoDir)
  68. }
  69. // MARK: - Optional Paths
  70. /// The root directory for build artifacts. If `nil`, a temporary directory will be used.
  71. let buildRoot: URL?
  72. /// The output directory for any artifacts generated during the build. If `nil`, a temporary
  73. /// directory will be used.
  74. let outputDir: URL?
  75. /// The path to where local podspecs are stored.
  76. let localPodspecPath: URL?
  77. /// The path to a directory to move all build logs to. If `nil`, a temporary directory will be
  78. /// used.
  79. var logsOutputDir: URL?
  80. /// Creates the struct containing all properties needed for a build.
  81. /// - Parameter repoDir: The root of the `firebase-ios-sdk` git repo.
  82. /// - Parameter buildRoot: The root directory for build artifacts. If `nil`, a temporary
  83. /// directory will be used.
  84. /// - Parameter outputDir: The output directory for any artifacts generated. If `nil`, a
  85. /// temporary directory will be used.
  86. /// - Parameter localPodspecPath: A path to where local podspecs are stored.
  87. /// - Parameter logsOutputDir: The output directory for any logs. If `nil`, a temporary
  88. /// directory will be used.
  89. init(repoDir: URL,
  90. buildRoot: URL?,
  91. outputDir: URL?,
  92. localPodspecPath: URL?,
  93. logsOutputDir: URL?) {
  94. self.repoDir = repoDir
  95. self.buildRoot = buildRoot
  96. self.outputDir = outputDir
  97. self.localPodspecPath = localPodspecPath
  98. self.logsOutputDir = logsOutputDir
  99. }
  100. /// Returns the expected template directory given the repo directory provided.
  101. static func templateDir(fromRepoDir repoDir: URL) -> URL {
  102. return repoDir.appendingPathComponents(["ReleaseTooling", "Template"])
  103. }
  104. }
  105. /// Paths needed throughout the process of packaging the Zip file.
  106. public let paths: FilesystemPaths
  107. /// The platforms to target for the builds.
  108. public let platforms: [Platform]
  109. /// Specifies if the builder is building dynamic frameworks instead of static frameworks.
  110. private let dynamicFrameworks: Bool
  111. /// Custom CocoaPods spec repos to be used. If not provided, the tool will only use the CocoaPods
  112. /// master repo.
  113. private let customSpecRepos: [URL]?
  114. /// Creates a ZipBuilder struct to build and assemble zip files and Carthage builds.
  115. ///
  116. /// - Parameters:
  117. /// - paths: Paths that are needed throughout the process of packaging the Zip file.
  118. /// - platforms: The platforms to target for the builds.
  119. /// - dynamicFrameworks: Specifies if dynamic frameworks should be built, otherwise static
  120. /// frameworks are built.
  121. /// - customSpecRepo: A custom spec repo to be used for fetching CocoaPods from.
  122. init(paths: FilesystemPaths,
  123. platforms: [Platform],
  124. dynamicFrameworks: Bool,
  125. customSpecRepos: [URL]? = nil) {
  126. self.paths = paths
  127. self.platforms = platforms
  128. self.customSpecRepos = customSpecRepos
  129. self.dynamicFrameworks = dynamicFrameworks
  130. }
  131. /// Builds and assembles the contents for the zip build.
  132. ///
  133. /// - Parameter podsToInstall: All pods to install.
  134. /// - Parameter includeCarthage: Build Carthage distribution as well.
  135. /// - Parameter includeDependencies: Include dependencies of requested pod in distribution.
  136. /// - Returns: Arrays of pod install info and the frameworks installed.
  137. func buildAndAssembleZip(podsToInstall: [CocoaPodUtils.VersionedPod],
  138. includeCarthage: Bool,
  139. includeDependencies: Bool) ->
  140. ([String: CocoaPodUtils.PodInfo], [String: [URL]], URL?) {
  141. // Remove CocoaPods cache so the build gets updates after a version is rebuilt during the
  142. // release process. Always do this, since it can be the source of subtle failures on rebuilds.
  143. CocoaPodUtils.cleanPodCache()
  144. // We need to install all the pods in order to get every single framework that we'll need
  145. // for the zip file. We can't install each one individually since some pods depend on different
  146. // subspecs from the same pod (ex: GoogleUtilities, GoogleToolboxForMac, etc). All of the code
  147. // wouldn't be included so we need to install all of the subspecs to catch the superset of all
  148. // required frameworks, then use that as the source of frameworks to pull from when including
  149. // the folders in each product directory.
  150. let linkage: CocoaPodUtils.LinkageType = dynamicFrameworks ? .dynamic : .standardStatic
  151. var groupedFrameworks: [String: [URL]] = [:]
  152. var carthageCoreDiagnosticsFrameworks: [URL] = []
  153. var podsBuilt: [String: CocoaPodUtils.PodInfo] = [:]
  154. var xcframeworks: [String: [URL]] = [:]
  155. var resources: [String: URL] = [:]
  156. for platform in platforms {
  157. let projectDir = FileManager.default.temporaryDirectory(withName: "project-" + platform.name)
  158. CocoaPodUtils.podInstallPrepare(inProjectDir: projectDir, templateDir: paths.templateDir)
  159. let platformPods = podsToInstall.filter { $0.platforms.contains(platform.name) }
  160. CocoaPodUtils.installPods(platformPods,
  161. inDir: projectDir,
  162. platform: platform,
  163. customSpecRepos: customSpecRepos,
  164. localPodspecPath: paths.localPodspecPath,
  165. linkage: linkage)
  166. // Find out what pods were installed with the above commands.
  167. let installedPods = CocoaPodUtils.installedPodsInfo(inProjectDir: projectDir,
  168. localPodspecPath: paths.localPodspecPath)
  169. // If module maps are needed for static frameworks, build them here to be available to copy
  170. // into the generated frameworks.
  171. if !dynamicFrameworks {
  172. ModuleMapBuilder(customSpecRepos: customSpecRepos,
  173. selectedPods: installedPods,
  174. platform: platform,
  175. paths: paths).build()
  176. }
  177. let podsToBuild = includeDependencies ? installedPods : installedPods.filter {
  178. platformPods.map { $0.name.components(separatedBy: "/").first }.contains($0.key)
  179. }
  180. // Build in a sorted order to make the build deterministic and to avoid exposing random
  181. // build order bugs.
  182. // Also AppCheck must be built after other pods so that its restricted architecture
  183. // selection does not restrict any of its dependencies.
  184. var sortedPods = podsToBuild.keys.sorted()
  185. // Interop pods are protocols only and should not be built.
  186. sortedPods.removeAll(where: { value in
  187. value.hasSuffix("Interop")
  188. })
  189. sortedPods.removeAll(where: { value in
  190. value == "FirebaseAppCheck"
  191. })
  192. sortedPods.append("FirebaseAppCheck")
  193. for podName in sortedPods {
  194. guard let podInfo = podsToBuild[podName] else {
  195. continue
  196. }
  197. if podName == "Firebase" {
  198. // Don't build the Firebase pod.
  199. } else if podInfo.isSourcePod {
  200. let builder = FrameworkBuilder(projectDir: projectDir,
  201. targetPlatforms: platform.platformTargets,
  202. dynamicFrameworks: dynamicFrameworks)
  203. let (frameworks, resourceContents) =
  204. builder.compileFrameworkAndResources(withName: podName,
  205. logsOutputDir: paths.logsOutputDir,
  206. setCarthage: false,
  207. podInfo: podInfo)
  208. groupedFrameworks[podName] = (groupedFrameworks[podName] ?? []) + frameworks
  209. if includeCarthage, podName == "FirebaseCoreDiagnostics" {
  210. let (cdFrameworks, _) = builder.compileFrameworkAndResources(withName: podName,
  211. logsOutputDir: paths
  212. .logsOutputDir,
  213. setCarthage: true,
  214. podInfo: podInfo)
  215. carthageCoreDiagnosticsFrameworks += cdFrameworks
  216. }
  217. if resourceContents != nil {
  218. resources[podName] = resourceContents
  219. }
  220. } else if podsBuilt[podName] == nil {
  221. // Binary pods need to be collected once, since the platforms should already be merged.
  222. let binaryFrameworks = collectBinaryFrameworks(fromPod: podName, podInfo: podInfo)
  223. xcframeworks[podName] = binaryFrameworks
  224. }
  225. // Union all pods built across platforms.
  226. // Be conservative and favor iOS if it exists - and workaround
  227. // bug where Firebase.h doesn't get installed for tvOS and macOS.
  228. // Fixed in #7284.
  229. if podsBuilt[podName] == nil {
  230. podsBuilt[podName] = podInfo
  231. }
  232. }
  233. }
  234. // Now consolidate the built frameworks for all platforms into a single xcframework.
  235. let xcframeworksDir = FileManager.default.temporaryDirectory(withName: "xcframeworks")
  236. do {
  237. try FileManager.default.createDirectory(at: xcframeworksDir,
  238. withIntermediateDirectories: false)
  239. } catch {
  240. fatalError("Could not create XCFrameworks directory: \(error)")
  241. }
  242. for groupedFramework in groupedFrameworks {
  243. let name = groupedFramework.key
  244. let xcframework = FrameworkBuilder.makeXCFramework(withName: name,
  245. frameworks: groupedFramework.value,
  246. xcframeworksDir: xcframeworksDir,
  247. resourceContents: resources[name])
  248. xcframeworks[name] = [xcframework]
  249. }
  250. for (framework, paths) in xcframeworks {
  251. print("Frameworks for pod: \(framework) were compiled at \(paths)")
  252. }
  253. guard includeCarthage else {
  254. // No Carthage build necessary, return now.
  255. return (podsBuilt, xcframeworks, nil)
  256. }
  257. let xcframeworksCarthageDir = FileManager.default.temporaryDirectory(withName: "xcf-carthage")
  258. do {
  259. try FileManager.default.createDirectory(at: xcframeworksCarthageDir,
  260. withIntermediateDirectories: false)
  261. } catch {
  262. fatalError("Could not create XCFrameworks Carthage directory: \(error)")
  263. }
  264. let carthageCoreDiagnosticsXcframework = FrameworkBuilder.makeXCFramework(
  265. withName: "FirebaseCoreDiagnostics",
  266. frameworks: carthageCoreDiagnosticsFrameworks,
  267. xcframeworksDir: xcframeworksCarthageDir,
  268. resourceContents: nil
  269. )
  270. return (podsBuilt, xcframeworks, carthageCoreDiagnosticsXcframework)
  271. }
  272. /// Try to build and package the contents of the Zip file. This will throw an error as soon as it
  273. /// encounters an error, or will quit due to a fatal error with the appropriate log.
  274. ///
  275. /// - Parameter templateDir: The template project for pod install.
  276. /// - Throws: One of many errors that could have happened during the build phase.
  277. func buildAndAssembleFirebaseRelease(templateDir: URL) throws -> ReleaseArtifacts {
  278. let manifest = FirebaseManifest.shared
  279. var podsToInstall = manifest.pods.map {
  280. CocoaPodUtils.VersionedPod(name: $0.name,
  281. version: manifest.versionString($0),
  282. platforms: $0.platforms)
  283. }
  284. guard !podsToInstall.isEmpty else {
  285. fatalError("Failed to find versions for Firebase release")
  286. }
  287. // We don't release Google-Mobile-Ads-SDK and GoogleSignIn, but we include their latest
  288. // version for convenience in the Zip and Carthage builds.
  289. podsToInstall.append(CocoaPodUtils.VersionedPod(name: "Google-Mobile-Ads-SDK",
  290. version: nil,
  291. platforms: ["ios"]))
  292. podsToInstall.append(CocoaPodUtils.VersionedPod(name: "GoogleSignIn",
  293. version: nil,
  294. platforms: ["ios"]))
  295. print("Final expected versions for the Zip file: \(podsToInstall)")
  296. let (installedPods, frameworks, carthageCoreDiagnosticsXcframeworkFirebase) =
  297. buildAndAssembleZip(podsToInstall: podsToInstall,
  298. includeCarthage: true,
  299. // Always include dependencies for Firebase zips.
  300. includeDependencies: true)
  301. // We need the Firebase pod to get the version for Carthage and to copy the `Firebase.h` and
  302. // `module.modulemap` file from it.
  303. guard let firebasePod = installedPods["Firebase"] else {
  304. fatalError("Could not get the Firebase pod from list of installed pods. All pods " +
  305. "installed: \(installedPods)")
  306. }
  307. guard let carthageCoreDiagnosticsXcframework = carthageCoreDiagnosticsXcframeworkFirebase else {
  308. fatalError("CoreDiagnosticsXcframework is missing")
  309. }
  310. let zipDir = try assembleDistributions(withPackageKind: "Firebase",
  311. podsToInstall: podsToInstall,
  312. installedPods: installedPods,
  313. frameworksToAssemble: frameworks,
  314. firebasePod: firebasePod)
  315. // Replace Core Diagnostics
  316. var carthageFrameworks = frameworks
  317. carthageFrameworks["FirebaseCoreDiagnostics"] = [carthageCoreDiagnosticsXcframework]
  318. let carthageDir = try assembleDistributions(withPackageKind: "CarthageFirebase",
  319. podsToInstall: podsToInstall,
  320. installedPods: installedPods,
  321. frameworksToAssemble: carthageFrameworks,
  322. firebasePod: firebasePod)
  323. return ReleaseArtifacts(firebaseVersion: firebasePod.version,
  324. zipDir: zipDir, carthageDir: carthageDir)
  325. }
  326. // MARK: - Private
  327. /// Assemble the folder structure of the Zip file. In order to get the frameworks
  328. /// required, we will `pod install` only those subspecs and then fetch the information for all
  329. /// the frameworks that were installed, copying the frameworks from our list of compiled
  330. /// frameworks. The whole process is:
  331. /// 1. Copy any required files (headers, modulemap, etc) over beforehand to fail fast if anything
  332. /// is misconfigured.
  333. /// 2. Get the frameworks required for Analytics, copy them to the Analytics folder.
  334. /// 3. Go through the rest of the subspecs (excluding those included in Analytics) and copy them
  335. /// to a folder with the name of the subspec.
  336. /// 4. Assemble the `README` file based off the template and copy it to the directory.
  337. /// 5. Return the URL of the folder containing the contents of the Zip file.
  338. ///
  339. /// - Returns: Return the URL of the folder containing the contents of the Zip or Carthage distribution.
  340. /// - Throws: One of many errors that could have happened during the build phase.
  341. private func assembleDistributions(withPackageKind packageKind: String,
  342. podsToInstall: [CocoaPodUtils.VersionedPod],
  343. installedPods: [String: CocoaPodUtils.PodInfo],
  344. frameworksToAssemble: [String: [URL]],
  345. firebasePod: CocoaPodUtils.PodInfo) throws -> URL {
  346. // Create the directory that will hold all the contents of the Zip file.
  347. let fileManager = FileManager.default
  348. let zipDir = fileManager.temporaryDirectory(withName: packageKind)
  349. do {
  350. if fileManager.directoryExists(at: zipDir) {
  351. try fileManager.removeItem(at: zipDir)
  352. }
  353. try fileManager.createDirectory(at: zipDir,
  354. withIntermediateDirectories: true,
  355. attributes: nil)
  356. }
  357. // Copy all required files from the Firebase pod. This will cause a fatalError if anything
  358. // fails.
  359. copyFirebasePodFiles(fromDir: firebasePod.installedLocation, to: zipDir)
  360. // Start with installing Analytics, since we'll need to exclude those frameworks from the rest
  361. // of the folders.
  362. let analyticsFrameworks: [String]
  363. let analyticsDir: URL
  364. do {
  365. // This returns the Analytics directory and a list of framework names that Analytics requires.
  366. /// Example: ["FirebaseInstallations, "GoogleAppMeasurement", "nanopb", <...>]
  367. let (dir, frameworks) = try installAndCopyFrameworks(forPod: "FirebaseAnalyticsSwift",
  368. inFolder: "FirebaseAnalytics",
  369. withInstalledPods: installedPods,
  370. rootZipDir: zipDir,
  371. builtFrameworks: frameworksToAssemble)
  372. analyticsFrameworks = frameworks
  373. analyticsDir = dir
  374. } catch {
  375. fatalError("Could not copy frameworks from Analytics into the zip file: \(error)")
  376. }
  377. // Start the README dependencies string with the frameworks built in Analytics.
  378. var readmeDeps = dependencyString(for: "FirebaseAnalyticsSwift",
  379. in: analyticsDir,
  380. frameworks: analyticsFrameworks)
  381. // Loop through all the other subspecs that aren't Core and Analytics and write them to their
  382. // final destination, including resources.
  383. let analyticsPods = analyticsFrameworks.map {
  384. $0.replacingOccurrences(of: ".framework", with: "")
  385. }
  386. let manifest = FirebaseManifest.shared
  387. let firebaseZipPods = manifest.pods.filter { $0.zip }.map { $0.name }
  388. // Skip Analytics and the pods bundled with it.
  389. let remainingPods = installedPods.filter {
  390. $0.key == "Google-Mobile-Ads-SDK" ||
  391. $0.key == "GoogleSignIn" ||
  392. (firebaseZipPods.contains($0.key) &&
  393. $0.key != "FirebaseAnalyticsSwift" &&
  394. $0.key != "Firebase" &&
  395. podsToInstall.map { $0.name }.contains($0.key))
  396. }.sorted { $0.key < $1.key }
  397. for pod in remainingPods {
  398. let folder = pod.key.replacingOccurrences(of: "Swift", with: "")
  399. do {
  400. if frameworksToAssemble[pod.key] == nil {
  401. // Continue if the pod wasn't built.
  402. continue
  403. }
  404. let (productDir, podFrameworks) =
  405. try installAndCopyFrameworks(forPod: pod.key,
  406. inFolder: folder,
  407. withInstalledPods: installedPods,
  408. rootZipDir: zipDir,
  409. builtFrameworks: frameworksToAssemble,
  410. podsToIgnore: analyticsPods)
  411. // Update the README.
  412. readmeDeps += dependencyString(for: folder, in: productDir, frameworks: podFrameworks)
  413. } catch {
  414. fatalError("Could not copy frameworks from \(pod) into the zip file: \(error)")
  415. }
  416. do {
  417. // Update Resources: For the zip distribution, they get pulled from the xcframework to the
  418. // top-level product directory. For the Carthage distribution, they propagate to each
  419. // individual framework.
  420. // TODO: Investigate changing the zip distro to also have Resources in the .frameworks to
  421. // enable different platform Resources.
  422. let productPath = zipDir.appendingPathComponent(folder)
  423. let contents = try fileManager.contentsOfDirectory(atPath: productPath.path)
  424. for fileOrFolder in contents {
  425. let xcPath = productPath.appendingPathComponent(fileOrFolder)
  426. let xcResourceDir = xcPath.appendingPathComponent("Resources")
  427. // Ignore anything that not an xcframework with Resources
  428. guard fileManager.isDirectory(at: xcPath),
  429. xcPath.lastPathComponent.hasSuffix("xcframework"),
  430. fileManager.directoryExists(at: xcResourceDir) else { continue }
  431. if packageKind == "Firebase" {
  432. // Move all the bundles in the frameworks out to a common "Resources" directory to
  433. // match the existing Zip structure.
  434. let resourcesDir = productPath.appendingPathComponent("Resources")
  435. try fileManager.moveItem(at: xcResourceDir, to: resourcesDir)
  436. } else {
  437. let xcContents = try fileManager.contentsOfDirectory(atPath: xcPath.path)
  438. for fileOrFolder in xcContents {
  439. let platformPath = xcPath.appendingPathComponent(fileOrFolder)
  440. guard fileManager.isDirectory(at: platformPath) else { continue }
  441. let platformContents = try fileManager.contentsOfDirectory(atPath: platformPath.path)
  442. for fileOrFolder in platformContents {
  443. let frameworkPath = platformPath.appendingPathComponent(fileOrFolder)
  444. // Ignore anything that not a framework.
  445. guard fileManager.isDirectory(at: frameworkPath),
  446. frameworkPath.lastPathComponent.hasSuffix("framework") else { continue }
  447. let resourcesDir = frameworkPath.appendingPathComponent("Resources")
  448. try fileManager.copyItem(at: xcResourceDir, to: resourcesDir)
  449. }
  450. }
  451. try fileManager.removeItem(at: xcResourceDir)
  452. }
  453. }
  454. } catch {
  455. fatalError("Could not setup Resources for \(pod) for \(packageKind) \(error)")
  456. }
  457. // Special case for Crashlytics:
  458. // Copy additional tools to avoid users from downloading another artifact to upload symbols.
  459. let crashlyticsPodName = "FirebaseCrashlytics"
  460. if pod.key == crashlyticsPodName {
  461. for file in ["upload-symbols", "run"] {
  462. let source = pod.value.installedLocation.appendingPathComponent(file)
  463. let target = zipDir.appendingPathComponent(crashlyticsPodName)
  464. .appendingPathComponent(file)
  465. do {
  466. try fileManager.copyItem(at: source, to: target)
  467. } catch {
  468. fatalError("Error copying Crashlytics tools from \(source) to \(target): \(error)")
  469. }
  470. }
  471. }
  472. }
  473. // Assemble the README. Start with the version text, then use the template to inject the
  474. // versions and the list of frameworks to include for each pod.
  475. let readmePath = paths.templateDir.appendingPathComponent(Constants.ProjectPath.readmeName)
  476. let readmeTemplate: String
  477. do {
  478. readmeTemplate = try String(contentsOf: readmePath)
  479. } catch {
  480. fatalError("Could not get contents of the README template: \(error)")
  481. }
  482. let versionsText = versionsString(for: installedPods)
  483. let readmeText = readmeTemplate.replacingOccurrences(of: "__INTEGRATION__", with: readmeDeps)
  484. .replacingOccurrences(of: "__VERSIONS__", with: versionsText)
  485. do {
  486. try readmeText.write(to: zipDir.appendingPathComponent(Constants.ProjectPath.readmeName),
  487. atomically: true,
  488. encoding: .utf8)
  489. } catch {
  490. fatalError("Could not write README to Zip directory: \(error)")
  491. }
  492. print("Contents of the packaged release were assembled at: \(zipDir)")
  493. return zipDir
  494. }
  495. /// Copies all frameworks from the `InstalledPod` (pulling from the `frameworkLocations`) and copy
  496. /// them to the destination directory.
  497. ///
  498. /// - Parameters:
  499. /// - installedPods: Names of all the pods installed, which will be used as a
  500. /// list to find out what frameworks to copy to the destination.
  501. /// - dir: Destination directory for all the frameworks.
  502. /// - frameworkLocations: A dictionary containing the pod name as the key and a location to
  503. /// the compiled frameworks.
  504. /// - ignoreFrameworks: A list of Pod
  505. /// - Returns: The filenames of the frameworks that were copied.
  506. /// - Throws: Various FileManager errors in case the copying fails, or an error if the framework
  507. /// doesn't exist in `frameworkLocations`.
  508. @discardableResult
  509. func copyFrameworks(fromPods installedPods: [String],
  510. toDirectory dir: URL,
  511. frameworkLocations: [String: [URL]],
  512. podsToIgnore: [String] = []) throws -> [String] {
  513. let fileManager = FileManager.default
  514. if !fileManager.directoryExists(at: dir) {
  515. try fileManager.createDirectory(at: dir, withIntermediateDirectories: false, attributes: nil)
  516. }
  517. // Keep track of the names of the frameworks copied over.
  518. var copiedFrameworkNames: [String] = []
  519. // Loop through each installedPod item and get the name so we can fetch the framework and copy
  520. // it to the destination directory.
  521. for podName in installedPods {
  522. // Skip the Firebase pod and specifically ignored frameworks.
  523. guard podName != "Firebase",
  524. !podName.hasSuffix("Interop"),
  525. !podsToIgnore.contains(podName) else {
  526. continue
  527. }
  528. guard let xcframeworks = frameworkLocations[podName] else {
  529. let reason = "Unable to find frameworks for \(podName) in cache of frameworks built to " +
  530. "include in the Zip file for that framework's folder."
  531. let error = NSError(domain: "com.firebase.zipbuilder",
  532. code: 1,
  533. userInfo: [NSLocalizedDescriptionKey: reason])
  534. throw error
  535. }
  536. // Copy each of the frameworks over, unless it's explicitly ignored.
  537. for xcframework in xcframeworks {
  538. let xcframeworkName = xcframework.lastPathComponent
  539. let destination = dir.appendingPathComponent(xcframeworkName)
  540. try fileManager.copyItem(at: xcframework, to: destination)
  541. copiedFrameworkNames
  542. .append(xcframeworkName.replacingOccurrences(of: ".xcframework", with: ""))
  543. }
  544. }
  545. return copiedFrameworkNames
  546. }
  547. /// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) into
  548. /// the given `zipDir`. Will cause a fatalError if anything fails since the zip file can't exist
  549. /// without these files.
  550. private func copyFirebasePodFiles(fromDir firebasePodDir: URL, to zipDir: URL) {
  551. let firebasePodFiles = ["NOTICES", "Sources/" + Constants.ProjectPath.firebaseHeader,
  552. "Sources/" + Constants.ProjectPath.modulemap]
  553. let firebaseFiles = firebasePodDir.appendingPathComponent("CoreOnly")
  554. let firebaseFilesToCopy = firebasePodFiles.map {
  555. firebaseFiles.appendingPathComponent($0)
  556. }
  557. // Copy each Firebase file.
  558. for file in firebaseFilesToCopy {
  559. // Each file should be copied to the destination project directory with the same name.
  560. let destination = zipDir.appendingPathComponent(file.lastPathComponent)
  561. do {
  562. if !FileManager.default.fileExists(atPath: destination.path) {
  563. print("Copying final distribution file \(file) to \(destination)...")
  564. try FileManager.default.copyItem(at: file, to: destination)
  565. }
  566. } catch {
  567. fatalError("Could not copy final distribution files to temporary directory before " +
  568. "building. Failed while attempting to copy \(file) to \(destination). \(error)")
  569. }
  570. }
  571. }
  572. /// Creates the String required for this pod to be added to the README. Creates a header and
  573. /// lists each framework in alphabetical order with the appropriate indentation, as well as a
  574. /// message about resources if they exist.
  575. ///
  576. /// - Parameters:
  577. /// - subspec: The subspec that requires documentation.
  578. /// - frameworks: All the frameworks required by the subspec.
  579. /// - includesResources: A flag to include or exclude the text for adding Resources.
  580. /// - Returns: A string with a header for the subspec name, and a list of frameworks required to
  581. /// integrate for the product to work. Formatted and ready for insertion into the
  582. /// README.
  583. private func dependencyString(for podName: String, in dir: URL, frameworks: [String]) -> String {
  584. var result = readmeHeader(podName: podName)
  585. for framework in frameworks.sorted() {
  586. // The .xcframework suffix has been stripped. The .framework suffix has not been.
  587. if framework.hasSuffix(".framework") {
  588. result += "- \(framework)\n"
  589. } else {
  590. result += "- \(framework).xcframework\n"
  591. }
  592. }
  593. result += "\n" // Necessary for Resource message to print properly in markdown.
  594. // Check if there is a Resources directory, and if so, add the disclaimer to the dependency
  595. // string.
  596. do {
  597. let fileManager = FileManager.default
  598. let resourceDirs = try fileManager.recursivelySearch(for: .directories(name: "Resources"),
  599. in: dir)
  600. if !resourceDirs.isEmpty {
  601. result += Constants.resourcesRequiredText
  602. result += "\n" // Separate from next pod in listing for text version.
  603. }
  604. } catch {
  605. fatalError("""
  606. Tried to find Resources directory for \(podName) in order to build the README, but an error
  607. occurred: \(error).
  608. """)
  609. }
  610. return result
  611. }
  612. /// Describes the dependency on other frameworks for the README file.
  613. func readmeHeader(podName: String) -> String {
  614. var header = "## \(podName)"
  615. if !(podName == "FirebaseAnalytics" || podName == "GoogleSignIn") {
  616. header += " (~> FirebaseAnalytics)"
  617. }
  618. header += "\n"
  619. return header
  620. }
  621. /// Installs a subspec and attempts to copy all the frameworks required for it from
  622. /// `buildFramework` and puts them into a new directory in the `rootZipDir` matching the
  623. /// subspec's name.
  624. ///
  625. /// - Parameters:
  626. /// - subspec: The subspec to install and get the dependencies list.
  627. /// - projectDir: Root of the project containing the Podfile.
  628. /// - rootZipDir: The root directory to be turned into the Zip file.
  629. /// - builtFrameworks: All frameworks that have been built, with the framework name as the key
  630. /// and the framework's location as the value.
  631. /// - podsToIgnore: Pods to avoid copying, if any.
  632. /// - Throws: Throws various errors from copying frameworks.
  633. /// - Returns: The product directory containing all frameworks and the names of the frameworks
  634. /// that were copied for this subspec.
  635. @discardableResult
  636. func installAndCopyFrameworks(forPod podName: String,
  637. inFolder folder: String,
  638. withInstalledPods installedPods: [String: CocoaPodUtils.PodInfo],
  639. rootZipDir: URL,
  640. builtFrameworks: [String: [URL]],
  641. podsToIgnore: [String] = []) throws -> (productDir: URL,
  642. frameworks: [String]) {
  643. let podsToCopy = [podName] +
  644. CocoaPodUtils.transitiveMasterPodDependencies(for: podName, in: installedPods)
  645. // Remove any duplicates from the `podsToCopy` array. The easiest way to do this is to wrap it
  646. // in a set then back to an array.
  647. let dedupedPods = Array(Set(podsToCopy))
  648. // Copy the frameworks into the proper product directory.
  649. let productDir = rootZipDir.appendingPathComponent(folder)
  650. let namedFrameworks = try copyFrameworks(fromPods: dedupedPods,
  651. toDirectory: productDir,
  652. frameworkLocations: builtFrameworks,
  653. podsToIgnore: podsToIgnore)
  654. let copiedFrameworks = namedFrameworks.filter {
  655. // Skip frameworks that aren't contained in the "podsToIgnore" array and the Firebase pod.
  656. !(podsToIgnore.contains($0) || $0 == "Firebase")
  657. }
  658. return (productDir, copiedFrameworks)
  659. }
  660. /// Creates the String that displays all the versions of each pod, in alphabetical order.
  661. ///
  662. /// - Parameter pods: All pods that were installed, with their versions.
  663. /// - Returns: A String to be added to the README.
  664. private func versionsString(for pods: [String: CocoaPodUtils.PodInfo]) -> String {
  665. // Get the longest name in order to generate padding with spaces so it looks nicer.
  666. let maxLength: Int = {
  667. guard let pod = pods.keys.max(by: { $0.count < $1.count }) else {
  668. // The longest pod as of this writing is 29 characters, if for whatever reason this fails
  669. // just assume 30 characters long.
  670. return 30
  671. }
  672. // Return room for a space afterwards.
  673. return pod.count + 1
  674. }()
  675. let header: String = {
  676. // Center the CocoaPods title within the spaces given. If there's an odd number of spaces, add
  677. // the extra space after the CocoaPods title.
  678. let cocoaPods = "CocoaPod"
  679. let spacesToPad = maxLength - cocoaPods.count
  680. let halfPadding = String(repeating: " ", count: spacesToPad / 2)
  681. // Start with the spaces padding, then add the CocoaPods title.
  682. var result = halfPadding + cocoaPods + halfPadding
  683. if spacesToPad % 2 != 0 {
  684. // Add an extra space since the padding isn't even
  685. result += " "
  686. }
  687. // Add the versioning text and return.
  688. result += "| Version\n"
  689. // Add a line underneath each.
  690. result += String(repeating: "-", count: maxLength) + "|" + String(repeating: "-", count: 9)
  691. result += "\n"
  692. return result
  693. }()
  694. // Sort the pods by name for a cleaner display.
  695. let sortedPods = pods.sorted { $0.key < $1.key }
  696. // Get the name and version of each pod, padding it along the way.
  697. var podVersions = ""
  698. for pod in sortedPods {
  699. // Insert the name and enough spaces to reach the end of the column.
  700. let podName = pod.key
  701. podVersions += podName + String(repeating: " ", count: maxLength - podName.count)
  702. // Add a pipe and the version.
  703. podVersions += "| " + pod.value.version + "\n"
  704. }
  705. return header + podVersions
  706. }
  707. // MARK: - Framework Generation
  708. /// Collects the .framework and .xcframeworks files from the binary pods. This will go through
  709. /// the contents of the directory and copy the .frameworks to a temporary directory. Returns a
  710. /// dictionary with the framework name for the key and all information for frameworks to install
  711. /// EXCLUDING resources, as they are handled later (if not included in the .framework file
  712. /// already).
  713. private func collectBinaryFrameworks(fromPod podName: String,
  714. podInfo: CocoaPodUtils.PodInfo) -> [URL] {
  715. // Verify the Pods folder exists and we can get the contents of it.
  716. let fileManager = FileManager.default
  717. // Create the temporary directory we'll be storing the build/assembled frameworks in, and remove
  718. // the Resources directory if it already exists.
  719. let binaryZipDir = fileManager.temporaryDirectory(withName: "binary_zip")
  720. do {
  721. try fileManager.createDirectory(at: binaryZipDir,
  722. withIntermediateDirectories: true,
  723. attributes: nil)
  724. } catch {
  725. fatalError("Cannot create temporary directory to store binary frameworks: \(error)")
  726. }
  727. var frameworks: [URL] = []
  728. // TODO: packageAllResources is disabled for binary frameworks since it's not needed for Firebase
  729. // and it does not yet support xcframeworks.
  730. // Package all resources into the frameworks since that's how Carthage needs it packaged.
  731. // do {
  732. // // TODO: Figure out if we need to exclude bundles here or not.
  733. // try ResourcesManager.packageAllResources(containedIn: podInfo.installedLocation)
  734. // } catch {
  735. // fatalError("Tried to package resources for \(podName) but it failed: \(error)")
  736. // }
  737. // Copy each of the frameworks to a known temporary directory and store the location.
  738. for framework in podInfo.binaryFrameworks {
  739. // Copy it to the temporary directory and save it to our list of frameworks.
  740. let zipLocation = binaryZipDir.appendingPathComponent(framework.lastPathComponent)
  741. // Remove the framework if it exists since it could be out of date.
  742. fileManager.removeIfExists(at: zipLocation)
  743. do {
  744. try fileManager.copyItem(at: framework, to: zipLocation)
  745. } catch {
  746. fatalError("Cannot copy framework at \(framework) while " +
  747. "attempting to generate frameworks. \(error)")
  748. }
  749. frameworks.append(zipLocation)
  750. }
  751. return frameworks
  752. }
  753. }