ZipBuilder.swift 39 KB

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