ZipBuilder.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. sortedPods.removeAll(where: { value in
  186. value == "FirebaseAppCheck"
  187. })
  188. sortedPods.append("FirebaseAppCheck")
  189. for podName in sortedPods {
  190. guard let podInfo = podsToBuild[podName] else {
  191. continue
  192. }
  193. if podName == "Firebase" {
  194. // Don't build the Firebase pod.
  195. } else if podInfo.isSourcePod {
  196. let builder = FrameworkBuilder(projectDir: projectDir,
  197. targetPlatforms: platform.platformTargets,
  198. dynamicFrameworks: dynamicFrameworks)
  199. let (frameworks, resourceContents) =
  200. builder.compileFrameworkAndResources(withName: podName,
  201. logsOutputDir: paths.logsOutputDir,
  202. setCarthage: false,
  203. podInfo: podInfo)
  204. groupedFrameworks[podName] = (groupedFrameworks[podName] ?? []) + frameworks
  205. if includeCarthage, podName == "FirebaseCoreDiagnostics" {
  206. let (cdFrameworks, _) = builder.compileFrameworkAndResources(withName: podName,
  207. logsOutputDir: paths
  208. .logsOutputDir,
  209. setCarthage: true,
  210. podInfo: podInfo)
  211. carthageCoreDiagnosticsFrameworks += cdFrameworks
  212. }
  213. if resourceContents != nil {
  214. resources[podName] = resourceContents
  215. }
  216. } else if podsBuilt[podName] == nil {
  217. // Binary pods need to be collected once, since the platforms should already be merged.
  218. let binaryFrameworks = collectBinaryFrameworks(fromPod: podName, podInfo: podInfo)
  219. xcframeworks[podName] = binaryFrameworks
  220. }
  221. // Union all pods built across platforms.
  222. // Be conservative and favor iOS if it exists - and workaround
  223. // bug where Firebase.h doesn't get installed for tvOS and macOS.
  224. // Fixed in #7284.
  225. if podsBuilt[podName] == nil {
  226. podsBuilt[podName] = podInfo
  227. }
  228. }
  229. }
  230. // Now consolidate the built frameworks for all platforms into a single xcframework.
  231. let xcframeworksDir = FileManager.default.temporaryDirectory(withName: "xcframeworks")
  232. do {
  233. try FileManager.default.createDirectory(at: xcframeworksDir,
  234. withIntermediateDirectories: false)
  235. } catch {
  236. fatalError("Could not create XCFrameworks directory: \(error)")
  237. }
  238. for groupedFramework in groupedFrameworks {
  239. let name = groupedFramework.key
  240. let xcframework = FrameworkBuilder.makeXCFramework(withName: name,
  241. frameworks: groupedFramework.value,
  242. xcframeworksDir: xcframeworksDir,
  243. resourceContents: resources[name])
  244. xcframeworks[name] = [xcframework]
  245. }
  246. for (framework, paths) in xcframeworks {
  247. print("Frameworks for pod: \(framework) were compiled at \(paths)")
  248. }
  249. guard includeCarthage else {
  250. // No Carthage build necessary, return now.
  251. return (podsBuilt, xcframeworks, nil)
  252. }
  253. let xcframeworksCarthageDir = FileManager.default.temporaryDirectory(withName: "xcf-carthage")
  254. do {
  255. try FileManager.default.createDirectory(at: xcframeworksCarthageDir,
  256. withIntermediateDirectories: false)
  257. } catch {
  258. fatalError("Could not create XCFrameworks Carthage directory: \(error)")
  259. }
  260. let carthageCoreDiagnosticsXcframework = FrameworkBuilder.makeXCFramework(
  261. withName: "FirebaseCoreDiagnostics",
  262. frameworks: carthageCoreDiagnosticsFrameworks,
  263. xcframeworksDir: xcframeworksCarthageDir,
  264. resourceContents: nil
  265. )
  266. return (podsBuilt, xcframeworks, carthageCoreDiagnosticsXcframework)
  267. }
  268. /// Try to build and package the contents of the Zip file. This will throw an error as soon as it
  269. /// encounters an error, or will quit due to a fatal error with the appropriate log.
  270. ///
  271. /// - Parameter templateDir: The template project for pod install.
  272. /// - Throws: One of many errors that could have happened during the build phase.
  273. func buildAndAssembleFirebaseRelease(templateDir: URL) throws -> ReleaseArtifacts {
  274. let manifest = FirebaseManifest.shared
  275. var podsToInstall = manifest.pods.map {
  276. CocoaPodUtils.VersionedPod(name: $0.name,
  277. version: manifest.versionString($0),
  278. platforms: $0.platforms)
  279. }
  280. guard !podsToInstall.isEmpty else {
  281. fatalError("Failed to find versions for Firebase release")
  282. }
  283. // We don't release Google-Mobile-Ads-SDK and GoogleSignIn, but we include their latest
  284. // version for convenience in the Zip and Carthage builds.
  285. podsToInstall.append(CocoaPodUtils.VersionedPod(name: "Google-Mobile-Ads-SDK",
  286. version: nil,
  287. platforms: ["ios"]))
  288. podsToInstall.append(CocoaPodUtils.VersionedPod(name: "GoogleSignIn",
  289. version: nil,
  290. platforms: ["ios"]))
  291. print("Final expected versions for the Zip file: \(podsToInstall)")
  292. let (installedPods, frameworks, carthageCoreDiagnosticsXcframeworkFirebase) =
  293. buildAndAssembleZip(podsToInstall: podsToInstall,
  294. includeCarthage: true,
  295. // Always include dependencies for Firebase zips.
  296. includeDependencies: true)
  297. // We need the Firebase pod to get the version for Carthage and to copy the `Firebase.h` and
  298. // `module.modulemap` file from it.
  299. guard let firebasePod = installedPods["Firebase"] else {
  300. fatalError("Could not get the Firebase pod from list of installed pods. All pods " +
  301. "installed: \(installedPods)")
  302. }
  303. guard let carthageCoreDiagnosticsXcframework = carthageCoreDiagnosticsXcframeworkFirebase else {
  304. fatalError("CoreDiagnosticsXcframework is missing")
  305. }
  306. let zipDir = try assembleDistributions(withPackageKind: "Firebase",
  307. podsToInstall: podsToInstall,
  308. installedPods: installedPods,
  309. frameworksToAssemble: frameworks,
  310. firebasePod: firebasePod)
  311. // Replace Core Diagnostics
  312. var carthageFrameworks = frameworks
  313. carthageFrameworks["FirebaseCoreDiagnostics"] = [carthageCoreDiagnosticsXcframework]
  314. let carthageDir = try assembleDistributions(withPackageKind: "CarthageFirebase",
  315. podsToInstall: podsToInstall,
  316. installedPods: installedPods,
  317. frameworksToAssemble: carthageFrameworks,
  318. firebasePod: firebasePod)
  319. return ReleaseArtifacts(firebaseVersion: firebasePod.version,
  320. zipDir: zipDir, carthageDir: carthageDir)
  321. }
  322. // MARK: - Private
  323. /// Assemble the folder structure of the Zip file. In order to get the frameworks
  324. /// required, we will `pod install` only those subspecs and then fetch the information for all
  325. /// the frameworks that were installed, copying the frameworks from our list of compiled
  326. /// frameworks. The whole process is:
  327. /// 1. Copy any required files (headers, modulemap, etc) over beforehand to fail fast if anything
  328. /// is misconfigured.
  329. /// 2. Get the frameworks required for Analytics, copy them to the Analytics folder.
  330. /// 3. Go through the rest of the subspecs (excluding those included in Analytics) and copy them
  331. /// to a folder with the name of the subspec.
  332. /// 4. Assemble the `README` file based off the template and copy it to the directory.
  333. /// 5. Return the URL of the folder containing the contents of the Zip file.
  334. ///
  335. /// - Returns: Return the URL of the folder containing the contents of the Zip or Carthage distribution.
  336. /// - Throws: One of many errors that could have happened during the build phase.
  337. private func assembleDistributions(withPackageKind packageKind: String,
  338. podsToInstall: [CocoaPodUtils.VersionedPod],
  339. installedPods: [String: CocoaPodUtils.PodInfo],
  340. frameworksToAssemble: [String: [URL]],
  341. firebasePod: CocoaPodUtils.PodInfo) throws -> URL {
  342. // Create the directory that will hold all the contents of the Zip file.
  343. let fileManager = FileManager.default
  344. let zipDir = fileManager.temporaryDirectory(withName: packageKind)
  345. do {
  346. if fileManager.directoryExists(at: zipDir) {
  347. try fileManager.removeItem(at: zipDir)
  348. }
  349. try fileManager.createDirectory(at: zipDir,
  350. withIntermediateDirectories: true,
  351. attributes: nil)
  352. }
  353. // Copy all required files from the Firebase pod. This will cause a fatalError if anything
  354. // fails.
  355. copyFirebasePodFiles(fromDir: firebasePod.installedLocation, to: zipDir)
  356. // Start with installing Analytics, since we'll need to exclude those frameworks from the rest
  357. // of the folders.
  358. let analyticsFrameworks: [String]
  359. let analyticsDir: URL
  360. do {
  361. // This returns the Analytics directory and a list of framework names that Analytics requires.
  362. /// Example: ["FirebaseInstallations, "GoogleAppMeasurement", "nanopb", <...>]
  363. let (dir, frameworks) = try installAndCopyFrameworks(forPod: "FirebaseAnalyticsSwift",
  364. inFolder: "FirebaseAnalytics",
  365. withInstalledPods: installedPods,
  366. rootZipDir: zipDir,
  367. builtFrameworks: frameworksToAssemble)
  368. analyticsFrameworks = frameworks
  369. analyticsDir = dir
  370. } catch {
  371. fatalError("Could not copy frameworks from Analytics into the zip file: \(error)")
  372. }
  373. // Start the README dependencies string with the frameworks built in Analytics.
  374. var readmeDeps = dependencyString(for: "FirebaseAnalyticsSwift",
  375. in: analyticsDir,
  376. frameworks: analyticsFrameworks)
  377. // Loop through all the other subspecs that aren't Core and Analytics and write them to their
  378. // final destination, including resources.
  379. let analyticsPods = analyticsFrameworks.map {
  380. $0.replacingOccurrences(of: ".framework", with: "")
  381. }
  382. let manifest = FirebaseManifest.shared
  383. let firebaseZipPods = manifest.pods.filter { $0.zip }.map { $0.name }
  384. // Skip Analytics and the pods bundled with it.
  385. let remainingPods = installedPods.filter {
  386. $0.key == "Google-Mobile-Ads-SDK" ||
  387. $0.key == "GoogleSignIn" ||
  388. (firebaseZipPods.contains($0.key) &&
  389. $0.key != "FirebaseAnalyticsSwift" &&
  390. $0.key != "Firebase" &&
  391. podsToInstall.map { $0.name }.contains($0.key))
  392. }.sorted { $0.key < $1.key }
  393. for pod in remainingPods {
  394. let folder = pod.key.replacingOccurrences(of: "Swift", with: "")
  395. do {
  396. if frameworksToAssemble[pod.key] == nil {
  397. // Continue if the pod wasn't built.
  398. continue
  399. }
  400. let (productDir, podFrameworks) =
  401. try installAndCopyFrameworks(forPod: pod.key,
  402. inFolder: folder,
  403. withInstalledPods: installedPods,
  404. rootZipDir: zipDir,
  405. builtFrameworks: frameworksToAssemble,
  406. podsToIgnore: analyticsPods)
  407. // Update the README.
  408. readmeDeps += dependencyString(for: folder, in: productDir, frameworks: podFrameworks)
  409. } catch {
  410. fatalError("Could not copy frameworks from \(pod) into the zip file: \(error)")
  411. }
  412. do {
  413. // Update Resources: For the zip distribution, they get pulled from the xcframework to the
  414. // top-level product directory. For the Carthage distribution, they propagate to each
  415. // individual framework.
  416. // TODO: Investigate changing the zip distro to also have Resources in the .frameworks to
  417. // enable different platform Resources.
  418. let productPath = zipDir.appendingPathComponent(folder)
  419. let contents = try fileManager.contentsOfDirectory(atPath: productPath.path)
  420. for fileOrFolder in contents {
  421. let xcPath = productPath.appendingPathComponent(fileOrFolder)
  422. let xcResourceDir = xcPath.appendingPathComponent("Resources")
  423. // Ignore anything that not an xcframework with Resources
  424. guard fileManager.isDirectory(at: xcPath),
  425. xcPath.lastPathComponent.hasSuffix("xcframework"),
  426. fileManager.directoryExists(at: xcResourceDir) else { continue }
  427. if packageKind == "Firebase" {
  428. // Move all the bundles in the frameworks out to a common "Resources" directory to
  429. // match the existing Zip structure.
  430. let resourcesDir = productPath.appendingPathComponent("Resources")
  431. try fileManager.moveItem(at: xcResourceDir, to: resourcesDir)
  432. } else {
  433. let xcContents = try fileManager.contentsOfDirectory(atPath: xcPath.path)
  434. for fileOrFolder in xcContents {
  435. let platformPath = xcPath.appendingPathComponent(fileOrFolder)
  436. guard fileManager.isDirectory(at: platformPath) else { continue }
  437. let platformContents = try fileManager.contentsOfDirectory(atPath: platformPath.path)
  438. for fileOrFolder in platformContents {
  439. let frameworkPath = platformPath.appendingPathComponent(fileOrFolder)
  440. // Ignore anything that not a framework.
  441. guard fileManager.isDirectory(at: frameworkPath),
  442. frameworkPath.lastPathComponent.hasSuffix("framework") else { continue }
  443. let resourcesDir = frameworkPath.appendingPathComponent("Resources")
  444. try fileManager.copyItem(at: xcResourceDir, to: resourcesDir)
  445. }
  446. }
  447. try fileManager.removeItem(at: xcResourceDir)
  448. }
  449. }
  450. } catch {
  451. fatalError("Could not setup Resources for \(pod) for \(packageKind) \(error)")
  452. }
  453. // Special case for Crashlytics:
  454. // Copy additional tools to avoid users from downloading another artifact to upload symbols.
  455. let crashlyticsPodName = "FirebaseCrashlytics"
  456. if pod.key == crashlyticsPodName {
  457. for file in ["upload-symbols", "run"] {
  458. let source = pod.value.installedLocation.appendingPathComponent(file)
  459. let target = zipDir.appendingPathComponent(crashlyticsPodName)
  460. .appendingPathComponent(file)
  461. do {
  462. try fileManager.copyItem(at: source, to: target)
  463. } catch {
  464. fatalError("Error copying Crashlytics tools from \(source) to \(target): \(error)")
  465. }
  466. }
  467. }
  468. }
  469. // Assemble the README. Start with the version text, then use the template to inject the
  470. // versions and the list of frameworks to include for each pod.
  471. let readmePath = paths.templateDir.appendingPathComponent(Constants.ProjectPath.readmeName)
  472. let readmeTemplate: String
  473. do {
  474. readmeTemplate = try String(contentsOf: readmePath)
  475. } catch {
  476. fatalError("Could not get contents of the README template: \(error)")
  477. }
  478. let versionsText = versionsString(for: installedPods)
  479. let readmeText = readmeTemplate.replacingOccurrences(of: "__INTEGRATION__", with: readmeDeps)
  480. .replacingOccurrences(of: "__VERSIONS__", with: versionsText)
  481. do {
  482. try readmeText.write(to: zipDir.appendingPathComponent(Constants.ProjectPath.readmeName),
  483. atomically: true,
  484. encoding: .utf8)
  485. } catch {
  486. fatalError("Could not write README to Zip directory: \(error)")
  487. }
  488. print("Contents of the packaged release were assembled at: \(zipDir)")
  489. return zipDir
  490. }
  491. /// Copies all frameworks from the `InstalledPod` (pulling from the `frameworkLocations`) and copy
  492. /// them to the destination directory.
  493. ///
  494. /// - Parameters:
  495. /// - installedPods: Names of all the pods installed, which will be used as a
  496. /// list to find out what frameworks to copy to the destination.
  497. /// - dir: Destination directory for all the frameworks.
  498. /// - frameworkLocations: A dictionary containing the pod name as the key and a location to
  499. /// the compiled frameworks.
  500. /// - ignoreFrameworks: A list of Pod
  501. /// - Returns: The filenames of the frameworks that were copied.
  502. /// - Throws: Various FileManager errors in case the copying fails, or an error if the framework
  503. /// doesn't exist in `frameworkLocations`.
  504. @discardableResult
  505. func copyFrameworks(fromPods installedPods: [String],
  506. toDirectory dir: URL,
  507. frameworkLocations: [String: [URL]],
  508. podsToIgnore: [String] = []) throws -> [String] {
  509. let fileManager = FileManager.default
  510. if !fileManager.directoryExists(at: dir) {
  511. try fileManager.createDirectory(at: dir, withIntermediateDirectories: false, attributes: nil)
  512. }
  513. // Keep track of the names of the frameworks copied over.
  514. var copiedFrameworkNames: [String] = []
  515. // Loop through each installedPod item and get the name so we can fetch the framework and copy
  516. // it to the destination directory.
  517. for podName in installedPods {
  518. // Skip the Firebase pod and specifically ignored frameworks.
  519. guard podName != "Firebase",
  520. !podsToIgnore.contains(podName) else {
  521. continue
  522. }
  523. guard let xcframeworks = frameworkLocations[podName] else {
  524. let reason = "Unable to find frameworks for \(podName) in cache of frameworks built to " +
  525. "include in the Zip file for that framework's folder."
  526. let error = NSError(domain: "com.firebase.zipbuilder",
  527. code: 1,
  528. userInfo: [NSLocalizedDescriptionKey: reason])
  529. throw error
  530. }
  531. // Copy each of the frameworks over, unless it's explicitly ignored.
  532. for xcframework in xcframeworks {
  533. let xcframeworkName = xcframework.lastPathComponent
  534. let destination = dir.appendingPathComponent(xcframeworkName)
  535. try fileManager.copyItem(at: xcframework, to: destination)
  536. copiedFrameworkNames
  537. .append(xcframeworkName.replacingOccurrences(of: ".xcframework", with: ""))
  538. }
  539. }
  540. return copiedFrameworkNames
  541. }
  542. /// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) into
  543. /// the given `zipDir`. Will cause a fatalError if anything fails since the zip file can't exist
  544. /// without these files.
  545. private func copyFirebasePodFiles(fromDir firebasePodDir: URL, to zipDir: URL) {
  546. let firebasePodFiles = ["NOTICES", "Sources/" + Constants.ProjectPath.firebaseHeader,
  547. "Sources/" + Constants.ProjectPath.modulemap]
  548. let firebaseFiles = firebasePodDir.appendingPathComponent("CoreOnly")
  549. let firebaseFilesToCopy = firebasePodFiles.map {
  550. firebaseFiles.appendingPathComponent($0)
  551. }
  552. // Copy each Firebase file.
  553. for file in firebaseFilesToCopy {
  554. // Each file should be copied to the destination project directory with the same name.
  555. let destination = zipDir.appendingPathComponent(file.lastPathComponent)
  556. do {
  557. if !FileManager.default.fileExists(atPath: destination.path) {
  558. print("Copying final distribution file \(file) to \(destination)...")
  559. try FileManager.default.copyItem(at: file, to: destination)
  560. }
  561. } catch {
  562. fatalError("Could not copy final distribution files to temporary directory before " +
  563. "building. Failed while attempting to copy \(file) to \(destination). \(error)")
  564. }
  565. }
  566. }
  567. /// Creates the String required for this pod to be added to the README. Creates a header and
  568. /// lists each framework in alphabetical order with the appropriate indentation, as well as a
  569. /// message about resources if they exist.
  570. ///
  571. /// - Parameters:
  572. /// - subspec: The subspec that requires documentation.
  573. /// - frameworks: All the frameworks required by the subspec.
  574. /// - includesResources: A flag to include or exclude the text for adding Resources.
  575. /// - Returns: A string with a header for the subspec name, and a list of frameworks required to
  576. /// integrate for the product to work. Formatted and ready for insertion into the
  577. /// README.
  578. private func dependencyString(for podName: String, in dir: URL, frameworks: [String]) -> String {
  579. var result = readmeHeader(podName: podName)
  580. for framework in frameworks.sorted() {
  581. // The .xcframework suffix has been stripped. The .framework suffix has not been.
  582. if framework.hasSuffix(".framework") {
  583. result += "- \(framework)\n"
  584. } else {
  585. result += "- \(framework).xcframework\n"
  586. }
  587. }
  588. result += "\n" // Necessary for Resource message to print properly in markdown.
  589. // Check if there is a Resources directory, and if so, add the disclaimer to the dependency
  590. // string.
  591. do {
  592. let fileManager = FileManager.default
  593. let resourceDirs = try fileManager.recursivelySearch(for: .directories(name: "Resources"),
  594. in: dir)
  595. if !resourceDirs.isEmpty {
  596. result += Constants.resourcesRequiredText
  597. result += "\n" // Separate from next pod in listing for text version.
  598. }
  599. } catch {
  600. fatalError("""
  601. Tried to find Resources directory for \(podName) in order to build the README, but an error
  602. occurred: \(error).
  603. """)
  604. }
  605. return result
  606. }
  607. /// Describes the dependency on other frameworks for the README file.
  608. func readmeHeader(podName: String) -> String {
  609. var header = "## \(podName)"
  610. if !(podName == "FirebaseAnalytics" || podName == "GoogleSignIn") {
  611. header += " (~> FirebaseAnalytics)"
  612. }
  613. header += "\n"
  614. return header
  615. }
  616. /// Installs a subspec and attempts to copy all the frameworks required for it from
  617. /// `buildFramework` and puts them into a new directory in the `rootZipDir` matching the
  618. /// subspec's name.
  619. ///
  620. /// - Parameters:
  621. /// - subspec: The subspec to install and get the dependencies list.
  622. /// - projectDir: Root of the project containing the Podfile.
  623. /// - rootZipDir: The root directory to be turned into the Zip file.
  624. /// - builtFrameworks: All frameworks that have been built, with the framework name as the key
  625. /// and the framework's location as the value.
  626. /// - podsToIgnore: Pods to avoid copying, if any.
  627. /// - Throws: Throws various errors from copying frameworks.
  628. /// - Returns: The product directory containing all frameworks and the names of the frameworks
  629. /// that were copied for this subspec.
  630. @discardableResult
  631. func installAndCopyFrameworks(forPod podName: String,
  632. inFolder folder: String,
  633. withInstalledPods installedPods: [String: CocoaPodUtils.PodInfo],
  634. rootZipDir: URL,
  635. builtFrameworks: [String: [URL]],
  636. podsToIgnore: [String] = []) throws -> (productDir: URL,
  637. frameworks: [String]) {
  638. let podsToCopy = [podName] +
  639. CocoaPodUtils.transitiveMasterPodDependencies(for: podName, in: installedPods)
  640. // Remove any duplicates from the `podsToCopy` array. The easiest way to do this is to wrap it
  641. // in a set then back to an array.
  642. let dedupedPods = Array(Set(podsToCopy))
  643. // Copy the frameworks into the proper product directory.
  644. let productDir = rootZipDir.appendingPathComponent(folder)
  645. let namedFrameworks = try copyFrameworks(fromPods: dedupedPods,
  646. toDirectory: productDir,
  647. frameworkLocations: builtFrameworks,
  648. podsToIgnore: podsToIgnore)
  649. let copiedFrameworks = namedFrameworks.filter {
  650. // Skip frameworks that aren't contained in the "podsToIgnore" array and the Firebase pod.
  651. !(podsToIgnore.contains($0) || $0 == "Firebase")
  652. }
  653. return (productDir, copiedFrameworks)
  654. }
  655. /// Creates the String that displays all the versions of each pod, in alphabetical order.
  656. ///
  657. /// - Parameter pods: All pods that were installed, with their versions.
  658. /// - Returns: A String to be added to the README.
  659. private func versionsString(for pods: [String: CocoaPodUtils.PodInfo]) -> String {
  660. // Get the longest name in order to generate padding with spaces so it looks nicer.
  661. let maxLength: Int = {
  662. guard let pod = pods.keys.max(by: { $0.count < $1.count }) else {
  663. // The longest pod as of this writing is 29 characters, if for whatever reason this fails
  664. // just assume 30 characters long.
  665. return 30
  666. }
  667. // Return room for a space afterwards.
  668. return pod.count + 1
  669. }()
  670. let header: String = {
  671. // Center the CocoaPods title within the spaces given. If there's an odd number of spaces, add
  672. // the extra space after the CocoaPods title.
  673. let cocoaPods = "CocoaPod"
  674. let spacesToPad = maxLength - cocoaPods.count
  675. let halfPadding = String(repeating: " ", count: spacesToPad / 2)
  676. // Start with the spaces padding, then add the CocoaPods title.
  677. var result = halfPadding + cocoaPods + halfPadding
  678. if spacesToPad % 2 != 0 {
  679. // Add an extra space since the padding isn't even
  680. result += " "
  681. }
  682. // Add the versioning text and return.
  683. result += "| Version\n"
  684. // Add a line underneath each.
  685. result += String(repeating: "-", count: maxLength) + "|" + String(repeating: "-", count: 9)
  686. result += "\n"
  687. return result
  688. }()
  689. // Sort the pods by name for a cleaner display.
  690. let sortedPods = pods.sorted { $0.key < $1.key }
  691. // Get the name and version of each pod, padding it along the way.
  692. var podVersions = ""
  693. for pod in sortedPods {
  694. // Insert the name and enough spaces to reach the end of the column.
  695. let podName = pod.key
  696. podVersions += podName + String(repeating: " ", count: maxLength - podName.count)
  697. // Add a pipe and the version.
  698. podVersions += "| " + pod.value.version + "\n"
  699. }
  700. return header + podVersions
  701. }
  702. // MARK: - Framework Generation
  703. /// Collects the .framework and .xcframeworks files from the binary pods. This will go through
  704. /// the contents of the directory and copy the .frameworks to a temporary directory. Returns a
  705. /// dictionary with the framework name for the key and all information for frameworks to install
  706. /// EXCLUDING resources, as they are handled later (if not included in the .framework file
  707. /// already).
  708. private func collectBinaryFrameworks(fromPod podName: String,
  709. podInfo: CocoaPodUtils.PodInfo) -> [URL] {
  710. // Verify the Pods folder exists and we can get the contents of it.
  711. let fileManager = FileManager.default
  712. // Create the temporary directory we'll be storing the build/assembled frameworks in, and remove
  713. // the Resources directory if it already exists.
  714. let binaryZipDir = fileManager.temporaryDirectory(withName: "binary_zip")
  715. do {
  716. try fileManager.createDirectory(at: binaryZipDir,
  717. withIntermediateDirectories: true,
  718. attributes: nil)
  719. } catch {
  720. fatalError("Cannot create temporary directory to store binary frameworks: \(error)")
  721. }
  722. var frameworks: [URL] = []
  723. // TODO: packageAllResources is disabled for binary frameworks since it's not needed for Firebase
  724. // and it does not yet support xcframeworks.
  725. // Package all resources into the frameworks since that's how Carthage needs it packaged.
  726. // do {
  727. // // TODO: Figure out if we need to exclude bundles here or not.
  728. // try ResourcesManager.packageAllResources(containedIn: podInfo.installedLocation)
  729. // } catch {
  730. // fatalError("Tried to package resources for \(podName) but it failed: \(error)")
  731. // }
  732. // Copy each of the frameworks to a known temporary directory and store the location.
  733. for framework in podInfo.binaryFrameworks {
  734. // Copy it to the temporary directory and save it to our list of frameworks.
  735. let zipLocation = binaryZipDir.appendingPathComponent(framework.lastPathComponent)
  736. // Remove the framework if it exists since it could be out of date.
  737. fileManager.removeIfExists(at: zipLocation)
  738. do {
  739. try fileManager.copyItem(at: framework, to: zipLocation)
  740. } catch {
  741. fatalError("Cannot copy framework at \(framework) while " +
  742. "attempting to generate frameworks. \(error)")
  743. }
  744. frameworks.append(zipLocation)
  745. }
  746. return frameworks
  747. }
  748. }