ZipBuilder.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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 carthageGoogleUtilitiesFrameworks: [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 == "GoogleUtilities" {
  206. let (cdFrameworks, _) = builder.compileFrameworkAndResources(withName: podName,
  207. logsOutputDir: paths
  208. .logsOutputDir,
  209. setCarthage: true,
  210. podInfo: podInfo)
  211. carthageGoogleUtilitiesFrameworks += 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 carthageGoogleUtilitiesXcframework = FrameworkBuilder.makeXCFramework(
  261. withName: "GoogleUtilities",
  262. frameworks: carthageGoogleUtilitiesFrameworks,
  263. xcframeworksDir: xcframeworksCarthageDir,
  264. resourceContents: nil
  265. )
  266. return (podsBuilt, xcframeworks, carthageGoogleUtilitiesXcframework)
  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, carthageGoogleUtilitiesXcframeworkFirebase) =
  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 carthageGoogleUtilitiesXcframework = carthageGoogleUtilitiesXcframeworkFirebase else {
  304. fatalError("GoogleUtilitiesXcframework 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["GoogleUtilities"] = [carthageGoogleUtilitiesXcframework]
  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 == "GoogleSignInSwiftSupport" ? "GoogleSignIn" :
  395. pod.key.replacingOccurrences(of: "Swift", with: "")
  396. do {
  397. if frameworksToAssemble[pod.key] == nil {
  398. // Continue if the pod wasn't built.
  399. continue
  400. }
  401. let (productDir, podFrameworks) =
  402. try installAndCopyFrameworks(forPod: pod.key,
  403. inFolder: folder,
  404. withInstalledPods: installedPods,
  405. rootZipDir: zipDir,
  406. builtFrameworks: frameworksToAssemble,
  407. frameworksToIgnore: analyticsPods)
  408. // Update the README.
  409. readmeDeps += dependencyString(for: folder, in: productDir, frameworks: podFrameworks)
  410. } catch {
  411. fatalError("Could not copy frameworks from \(pod) into the zip file: \(error)")
  412. }
  413. do {
  414. // Update Resources: For the zip distribution, they get pulled from the xcframework to the
  415. // top-level product directory. For the Carthage distribution, they propagate to each
  416. // individual framework.
  417. // TODO: Investigate changing the zip distro to also have Resources in the .frameworks to
  418. // enable different platform Resources.
  419. let productPath = zipDir.appendingPathComponent(folder)
  420. let contents = try fileManager.contentsOfDirectory(atPath: productPath.path)
  421. for fileOrFolder in contents {
  422. let xcPath = productPath.appendingPathComponent(fileOrFolder)
  423. let xcResourceDir = xcPath.appendingPathComponent("Resources")
  424. // Ignore anything that not an xcframework with Resources
  425. guard fileManager.isDirectory(at: xcPath),
  426. xcPath.lastPathComponent.hasSuffix("xcframework"),
  427. fileManager.directoryExists(at: xcResourceDir) else { continue }
  428. if packageKind == "Firebase" {
  429. // Move all the bundles in the frameworks out to a common "Resources" directory to
  430. // match the existing Zip structure.
  431. let resourcesDir = productPath.appendingPathComponent("Resources")
  432. try fileManager.moveItem(at: xcResourceDir, to: resourcesDir)
  433. } else {
  434. let xcContents = try fileManager.contentsOfDirectory(atPath: xcPath.path)
  435. for fileOrFolder in xcContents {
  436. let platformPath = xcPath.appendingPathComponent(fileOrFolder)
  437. guard fileManager.isDirectory(at: platformPath) else { continue }
  438. let platformContents = try fileManager.contentsOfDirectory(atPath: platformPath.path)
  439. for fileOrFolder in platformContents {
  440. let frameworkPath = platformPath.appendingPathComponent(fileOrFolder)
  441. // Ignore anything that not a framework.
  442. guard fileManager.isDirectory(at: frameworkPath),
  443. frameworkPath.lastPathComponent.hasSuffix("framework") else { continue }
  444. let resourcesDir = frameworkPath.appendingPathComponent("Resources")
  445. try fileManager.copyItem(at: xcResourceDir, to: resourcesDir)
  446. }
  447. }
  448. try fileManager.removeItem(at: xcResourceDir)
  449. }
  450. }
  451. } catch {
  452. fatalError("Could not setup Resources for \(pod) for \(packageKind) \(error)")
  453. }
  454. // Special case for Crashlytics:
  455. // Copy additional tools to avoid users from downloading another artifact to upload symbols.
  456. let crashlyticsPodName = "FirebaseCrashlytics"
  457. if pod.key == crashlyticsPodName {
  458. for file in ["upload-symbols", "run"] {
  459. let source = pod.value.installedLocation.appendingPathComponent(file)
  460. let target = zipDir.appendingPathComponent(crashlyticsPodName)
  461. .appendingPathComponent(file)
  462. do {
  463. try fileManager.copyItem(at: source, to: target)
  464. } catch {
  465. fatalError("Error copying Crashlytics tools from \(source) to \(target): \(error)")
  466. }
  467. }
  468. }
  469. }
  470. // Assemble the README. Start with the version text, then use the template to inject the
  471. // versions and the list of frameworks to include for each pod.
  472. let readmePath = paths.templateDir.appendingPathComponent(Constants.ProjectPath.readmeName)
  473. let readmeTemplate: String
  474. do {
  475. readmeTemplate = try String(contentsOf: readmePath)
  476. } catch {
  477. fatalError("Could not get contents of the README template: \(error)")
  478. }
  479. let versionsText = versionsString(for: installedPods)
  480. let readmeText = readmeTemplate.replacingOccurrences(of: "__INTEGRATION__", with: readmeDeps)
  481. .replacingOccurrences(of: "__VERSIONS__", with: versionsText)
  482. do {
  483. try readmeText.write(to: zipDir.appendingPathComponent(Constants.ProjectPath.readmeName),
  484. atomically: true,
  485. encoding: .utf8)
  486. } catch {
  487. fatalError("Could not write README to Zip directory: \(error)")
  488. }
  489. print("Contents of the packaged release were assembled at: \(zipDir)")
  490. return zipDir
  491. }
  492. /// Copies all frameworks from the `InstalledPod` (pulling from the `frameworkLocations`) and copy
  493. /// them to the destination directory.
  494. ///
  495. /// - Parameters:
  496. /// - installedPods: Names of all the pods installed, which will be used as a
  497. /// list to find out what frameworks to copy to the destination.
  498. /// - dir: Destination directory for all the frameworks.
  499. /// - frameworkLocations: A dictionary containing the pod name as the key and a location to
  500. /// the compiled frameworks.
  501. /// - ignoreFrameworks: A list of Pod
  502. /// - Returns: The filenames of the frameworks that were copied.
  503. /// - Throws: Various FileManager errors in case the copying fails, or an error if the framework
  504. /// doesn't exist in `frameworkLocations`.
  505. @discardableResult
  506. func copyFrameworks(fromPods installedPods: [String],
  507. toDirectory dir: URL,
  508. frameworkLocations: [String: [URL]],
  509. frameworksToIgnore: [String] = []) throws -> [String] {
  510. let fileManager = FileManager.default
  511. if !fileManager.directoryExists(at: dir) {
  512. try fileManager.createDirectory(at: dir, withIntermediateDirectories: false, attributes: nil)
  513. }
  514. // Keep track of the names of the frameworks copied over.
  515. var copiedFrameworkNames: [String] = []
  516. // Loop through each installedPod item and get the name so we can fetch the framework and copy
  517. // it to the destination directory.
  518. for podName in installedPods {
  519. // Skip the Firebase pod and specifically ignored frameworks.
  520. guard podName != "Firebase" 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 name = (xcframeworkName as NSString).deletingPathExtension
  535. if frameworksToIgnore.contains(name) {
  536. continue
  537. }
  538. let destination = dir.appendingPathComponent(xcframeworkName)
  539. try fileManager.copyItem(at: xcframework, to: destination)
  540. copiedFrameworkNames
  541. .append(xcframeworkName.replacingOccurrences(of: ".xcframework", with: ""))
  542. }
  543. }
  544. return copiedFrameworkNames
  545. }
  546. /// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) into
  547. /// the given `zipDir`. Will cause a fatalError if anything fails since the zip file can't exist
  548. /// without these files.
  549. private func copyFirebasePodFiles(fromDir firebasePodDir: URL, to zipDir: URL) {
  550. let firebasePodFiles = ["NOTICES", "Sources/" + Constants.ProjectPath.firebaseHeader,
  551. "Sources/" + Constants.ProjectPath.modulemap]
  552. let firebaseFiles = firebasePodDir.appendingPathComponent("CoreOnly")
  553. let firebaseFilesToCopy = firebasePodFiles.map {
  554. firebaseFiles.appendingPathComponent($0)
  555. }
  556. // Copy each Firebase file.
  557. for file in firebaseFilesToCopy {
  558. // Each file should be copied to the destination project directory with the same name.
  559. let destination = zipDir.appendingPathComponent(file.lastPathComponent)
  560. do {
  561. if !FileManager.default.fileExists(atPath: destination.path) {
  562. print("Copying final distribution file \(file) to \(destination)...")
  563. try FileManager.default.copyItem(at: file, to: destination)
  564. }
  565. } catch {
  566. fatalError("Could not copy final distribution files to temporary directory before " +
  567. "building. Failed while attempting to copy \(file) to \(destination). \(error)")
  568. }
  569. }
  570. }
  571. /// Creates the String required for this pod to be added to the README. Creates a header and
  572. /// lists each framework in alphabetical order with the appropriate indentation, as well as a
  573. /// message about resources if they exist.
  574. ///
  575. /// - Parameters:
  576. /// - subspec: The subspec that requires documentation.
  577. /// - frameworks: All the frameworks required by the subspec.
  578. /// - includesResources: A flag to include or exclude the text for adding Resources.
  579. /// - Returns: A string with a header for the subspec name, and a list of frameworks required to
  580. /// integrate for the product to work. Formatted and ready for insertion into the
  581. /// README.
  582. private func dependencyString(for podName: String, in dir: URL, frameworks: [String]) -> String {
  583. var result = readmeHeader(podName: podName)
  584. for framework in frameworks.sorted() {
  585. // The .xcframework suffix has been stripped. The .framework suffix has not been.
  586. if framework.hasSuffix(".framework") {
  587. result += "- \(framework)\n"
  588. } else {
  589. result += "- \(framework).xcframework\n"
  590. }
  591. }
  592. result += "\n" // Necessary for Resource message to print properly in markdown.
  593. // Check if there is a Resources directory, and if so, add the disclaimer to the dependency
  594. // string.
  595. do {
  596. let fileManager = FileManager.default
  597. let resourceDirs = try fileManager.recursivelySearch(for: .directories(name: "Resources"),
  598. in: dir)
  599. if !resourceDirs.isEmpty {
  600. result += Constants.resourcesRequiredText
  601. result += "\n" // Separate from next pod in listing for text version.
  602. }
  603. } catch {
  604. fatalError("""
  605. Tried to find Resources directory for \(podName) in order to build the README, but an error
  606. occurred: \(error).
  607. """)
  608. }
  609. return result
  610. }
  611. /// Describes the dependency on other frameworks for the README file.
  612. func readmeHeader(podName: String) -> String {
  613. var header = "## \(podName)"
  614. if !(podName == "FirebaseAnalytics" || podName == "GoogleSignIn") {
  615. header += " (~> FirebaseAnalytics)"
  616. }
  617. header += "\n"
  618. return header
  619. }
  620. /// Installs a subspec and attempts to copy all the frameworks required for it from
  621. /// `buildFramework` and puts them into a new directory in the `rootZipDir` matching the
  622. /// subspec's name.
  623. ///
  624. /// - Parameters:
  625. /// - subspec: The subspec to install and get the dependencies list.
  626. /// - projectDir: Root of the project containing the Podfile.
  627. /// - rootZipDir: The root directory to be turned into the Zip file.
  628. /// - builtFrameworks: All frameworks that have been built, with the framework name as the key
  629. /// and the framework's location as the value.
  630. /// - podsToIgnore: Pods to avoid copying, if any.
  631. /// - Throws: Throws various errors from copying frameworks.
  632. /// - Returns: The product directory containing all frameworks and the names of the frameworks
  633. /// that were copied for this subspec.
  634. @discardableResult
  635. func installAndCopyFrameworks(forPod podName: String,
  636. inFolder folder: String,
  637. withInstalledPods installedPods: [String: CocoaPodUtils.PodInfo],
  638. rootZipDir: URL,
  639. builtFrameworks: [String: [URL]],
  640. frameworksToIgnore: [String] = []) throws
  641. -> (productDir: URL, frameworks: [String]) {
  642. let podsToCopy = [podName] +
  643. CocoaPodUtils.transitiveMasterPodDependencies(for: podName, in: installedPods)
  644. // Remove any duplicates from the `podsToCopy` array. The easiest way to do this is to wrap it
  645. // in a set then back to an array.
  646. let dedupedPods = Array(Set(podsToCopy))
  647. // Copy the frameworks into the proper product directory.
  648. let productDir = rootZipDir.appendingPathComponent(folder)
  649. let namedFrameworks = try copyFrameworks(fromPods: dedupedPods,
  650. toDirectory: productDir,
  651. frameworkLocations: builtFrameworks,
  652. frameworksToIgnore: frameworksToIgnore)
  653. let copiedFrameworks = namedFrameworks.filter {
  654. // Skip frameworks that aren't contained in the "frameworksToIgnore" array and the Firebase pod.
  655. !(frameworksToIgnore.contains($0) || $0 == "Firebase")
  656. }
  657. return (productDir, copiedFrameworks)
  658. }
  659. /// Creates the String that displays all the versions of each pod, in alphabetical order.
  660. ///
  661. /// - Parameter pods: All pods that were installed, with their versions.
  662. /// - Returns: A String to be added to the README.
  663. private func versionsString(for pods: [String: CocoaPodUtils.PodInfo]) -> String {
  664. // Get the longest name in order to generate padding with spaces so it looks nicer.
  665. let maxLength: Int = {
  666. guard let pod = pods.keys.max(by: { $0.count < $1.count }) else {
  667. // The longest pod as of this writing is 29 characters, if for whatever reason this fails
  668. // just assume 30 characters long.
  669. return 30
  670. }
  671. // Return room for a space afterwards.
  672. return pod.count + 1
  673. }()
  674. let header: String = {
  675. // Center the CocoaPods title within the spaces given. If there's an odd number of spaces, add
  676. // the extra space after the CocoaPods title.
  677. let cocoaPods = "CocoaPod"
  678. let spacesToPad = maxLength - cocoaPods.count
  679. let halfPadding = String(repeating: " ", count: spacesToPad / 2)
  680. // Start with the spaces padding, then add the CocoaPods title.
  681. var result = halfPadding + cocoaPods + halfPadding
  682. if spacesToPad % 2 != 0 {
  683. // Add an extra space since the padding isn't even
  684. result += " "
  685. }
  686. // Add the versioning text and return.
  687. result += "| Version\n"
  688. // Add a line underneath each.
  689. result += String(repeating: "-", count: maxLength) + "|" + String(repeating: "-", count: 9)
  690. result += "\n"
  691. return result
  692. }()
  693. // Sort the pods by name for a cleaner display.
  694. let sortedPods = pods.sorted { $0.key < $1.key }
  695. // Get the name and version of each pod, padding it along the way.
  696. var podVersions = ""
  697. for pod in sortedPods {
  698. // Insert the name and enough spaces to reach the end of the column.
  699. let podName = pod.key
  700. podVersions += podName + String(repeating: " ", count: maxLength - podName.count)
  701. // Add a pipe and the version.
  702. podVersions += "| " + pod.value.version + "\n"
  703. }
  704. return header + podVersions
  705. }
  706. // MARK: - Framework Generation
  707. /// Collects the .framework and .xcframeworks files from the binary pods. This will go through
  708. /// the contents of the directory and copy the .frameworks to a temporary directory. Returns a
  709. /// dictionary with the framework name for the key and all information for frameworks to install
  710. /// EXCLUDING resources, as they are handled later (if not included in the .framework file
  711. /// already).
  712. private func collectBinaryFrameworks(fromPod podName: String,
  713. podInfo: CocoaPodUtils.PodInfo) -> [URL] {
  714. // Verify the Pods folder exists and we can get the contents of it.
  715. let fileManager = FileManager.default
  716. // Create the temporary directory we'll be storing the build/assembled frameworks in, and remove
  717. // the Resources directory if it already exists.
  718. let binaryZipDir = fileManager.temporaryDirectory(withName: "binary_zip")
  719. do {
  720. try fileManager.createDirectory(at: binaryZipDir,
  721. withIntermediateDirectories: true,
  722. attributes: nil)
  723. } catch {
  724. fatalError("Cannot create temporary directory to store binary frameworks: \(error)")
  725. }
  726. var frameworks: [URL] = []
  727. // TODO: packageAllResources is disabled for binary frameworks since it's not needed for Firebase
  728. // and it does not yet support xcframeworks.
  729. // Package all resources into the frameworks since that's how Carthage needs it packaged.
  730. // do {
  731. // // TODO: Figure out if we need to exclude bundles here or not.
  732. // try ResourcesManager.packageAllResources(containedIn: podInfo.installedLocation)
  733. // } catch {
  734. // fatalError("Tried to package resources for \(podName) but it failed: \(error)")
  735. // }
  736. // Copy each of the frameworks to a known temporary directory and store the location.
  737. for framework in podInfo.binaryFrameworks {
  738. // Copy it to the temporary directory and save it to our list of frameworks.
  739. let zipLocation = binaryZipDir.appendingPathComponent(framework.lastPathComponent)
  740. // Remove the framework if it exists since it could be out of date.
  741. fileManager.removeIfExists(at: zipLocation)
  742. do {
  743. try fileManager.copyItem(at: framework, to: zipLocation)
  744. } catch {
  745. fatalError("Cannot copy framework at \(framework) while " +
  746. "attempting to generate frameworks. \(error)")
  747. }
  748. frameworks.append(zipLocation)
  749. }
  750. return frameworks
  751. }
  752. }