ZipBuilder.swift 39 KB

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