check_imports.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #!/usr/bin/swift
  2. /*
  3. * Copyright 2020 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. // Utility script for verifying `import` and `include` syntax. This ensures a
  18. // consistent style as well as functionality across multiple package managers.
  19. // For more context, see https://github.com/firebase/firebase-ios-sdk/blob/main/HeadersImports.md.
  20. import Foundation
  21. // Skip these directories. Imports should only be repo-relative in libraries
  22. // and unit tests.
  23. let skipDirPatterns = ["/Sample/", "/Pods/",
  24. "FirebaseDynamicLinks/Tests/Integration",
  25. "FirebaseInAppMessaging/Tests/Integration/",
  26. "SymbolCollisionTest/", "/gen/",
  27. "IntegrationTesting/CocoapodsIntegrationTest/",
  28. "FirebasePerformance/Tests/TestApp/",
  29. "cmake-build-debug/", "build/", "ObjCIntegration/",
  30. "FirebasePerformance/Tests/FIRPerfE2E/"] +
  31. [
  32. "CoreOnly/Sources", // Skip Firebase.h.
  33. "SwiftPMTests", // The SwiftPM tests test module imports.
  34. "IntegrationTesting/ClientApp", // The ClientApp tests module imports.
  35. "FirebaseSessions/Protogen/", // Generated nanopb code with imports
  36. ] +
  37. // The following are temporary skips pending working through a first pass of the repo:
  38. [
  39. "FirebaseDatabase/Sources/third_party/Wrap-leveldb", // Pending SwiftPM for leveldb.
  40. "Example",
  41. "Firestore",
  42. "GoogleUtilitiesComponents",
  43. "FirebasePerformance/ProtoSupport/",
  44. ]
  45. // Skip existence test for patterns that start with the following:
  46. let skipImportPatterns = [
  47. "FBLPromise",
  48. "OCMock",
  49. "OCMStubRecorder",
  50. ]
  51. private class ErrorLogger {
  52. var foundError = false
  53. func log(_ message: String) {
  54. print(message)
  55. foundError = true
  56. }
  57. func importLog(_ message: String, _ file: String, _ line: Int) {
  58. log("Import Error: \(file):\(line) \(message)")
  59. }
  60. }
  61. private func checkFile(_ file: String, logger: ErrorLogger, inRepo repoURL: URL,
  62. isSwiftFile: Bool) {
  63. var fileContents = ""
  64. do {
  65. fileContents = try String(contentsOfFile: file, encoding: .utf8)
  66. } catch {
  67. logger.log("Could not read \(file). \(error)")
  68. // Not a source file, give up and return.
  69. return
  70. }
  71. guard !isSwiftFile else {
  72. // Swift specific checks.
  73. fileContents.components(separatedBy: .newlines)
  74. .enumerated() // [(lineNum, line), ...]
  75. .filter { $1.starts(with: "import FirebaseCoreExtension") }
  76. .forEach { lineNum, line in
  77. logger
  78. .importLog(
  79. "Use `@_implementationOnly import FirebaseCoreExtension` when importing `FirebaseCoreExtension`.",
  80. file, lineNum
  81. )
  82. }
  83. return
  84. }
  85. let isPublic = file.range(of: "/Public/") != nil &&
  86. // TODO: Skip legacy GDTCCTLibrary file that isn't Public and should be moved.
  87. // This test is used in the GoogleDataTransport's repo's CI clone of this repo.
  88. file.range(of: "GDTCCTLibrary/Public/GDTCOREvent+GDTCCTSupport.h") == nil
  89. let isPrivate = file.range(of: "/Sources/Private/") != nil ||
  90. // Delete when FirebaseInstallations fixes directory structure.
  91. file.range(of: "Source/Library/Private/FirebaseInstallationsInternal.h") != nil ||
  92. file.range(of: "FirebaseCore/Extension") != nil
  93. // Treat all files with names finishing on "Test" or "Tests" as files with tests.
  94. let isTestFile = file.contains("Test.m") || file.contains("Tests.m") ||
  95. file.contains("Test.swift") || file.contains("Tests.swift")
  96. let isBridgingHeader = file.contains("Bridging-Header.h")
  97. var inSwiftPackage = false
  98. var inSwiftPackageElse = false
  99. let lines = fileContents.components(separatedBy: .newlines)
  100. var lineNum = 0
  101. nextLine: for rawLine in lines {
  102. let line = rawLine.trimmingCharacters(in: .whitespaces)
  103. lineNum += 1
  104. if line.starts(with: "#if SWIFT_PACKAGE") {
  105. inSwiftPackage = true
  106. } else if inSwiftPackage, line.starts(with: "#else") {
  107. inSwiftPackage = false
  108. inSwiftPackageElse = true
  109. } else if inSwiftPackageElse, line.starts(with: "#endif") {
  110. inSwiftPackageElse = false
  111. } else if inSwiftPackage {
  112. continue
  113. } else if file.contains("FirebaseTestingSupport") {
  114. // Module imports ok in SPM only test infrastructure.
  115. continue
  116. }
  117. // "The #else of a SWIFT_PACKAGE check should only do CocoaPods module-style imports."
  118. if line.starts(with: "#import") || line.starts(with: "#include") {
  119. let importFile = line.components(separatedBy: " ")[1]
  120. if inSwiftPackageElse {
  121. if importFile.first != "<" {
  122. logger
  123. .importLog("Import in SWIFT_PACKAGE #else should start with \"<\".", file, lineNum)
  124. }
  125. continue
  126. }
  127. let importFileRaw = importFile.replacingOccurrences(of: "\"", with: "")
  128. .replacingOccurrences(of: "<", with: "")
  129. .replacingOccurrences(of: ">", with: "")
  130. if importFile.first == "\"" {
  131. // Public Headers should only use simple file names without paths.
  132. if isPublic {
  133. if importFile.contains("/") {
  134. logger.importLog("Public header import should not include \"/\"", file, lineNum)
  135. }
  136. } else if !FileManager.default.fileExists(atPath: repoURL.path + "/" + importFileRaw) {
  137. // Non-public header imports should be repo-relative paths. Unqualified imports are
  138. // allowed in private headers.
  139. if !isPrivate || importFile.contains("/") {
  140. for skip in skipImportPatterns {
  141. if importFileRaw.starts(with: skip) {
  142. continue nextLine
  143. }
  144. }
  145. logger.importLog("Import \(importFileRaw) does not exist.", file, lineNum)
  146. }
  147. }
  148. } else if importFile.first == "<", !isPrivate, !isTestFile, !isBridgingHeader, !isPublic {
  149. // Verify that double quotes are always used for intra-module imports.
  150. if importFileRaw.starts(with: "Firebase"),
  151. // Allow intra-module imports of FirebaseAppCheckInterop.
  152. // TODO: Remove the FirebaseAppCheckInterop exception when it's moved to a separate repo.
  153. importFile.range(of: "FirebaseAppCheckInterop/FirebaseAppCheckInterop.h") == nil {
  154. logger
  155. .importLog("Imports internal to the repo should use double quotes not \"<\"", file,
  156. lineNum)
  157. }
  158. }
  159. }
  160. }
  161. }
  162. private func main() -> Int32 {
  163. let logger = ErrorLogger()
  164. // Search the path upwards to find the root of the firebase-ios-sdk repo.
  165. var url = URL(fileURLWithPath: FileManager().currentDirectoryPath)
  166. while url.path != "/" {
  167. let script = url.appendingPathComponent("scripts/check_imports.swift")
  168. if FileManager.default.fileExists(atPath: script.path) {
  169. break
  170. }
  171. url = url.deletingLastPathComponent()
  172. }
  173. let repoURL = url
  174. guard let contents = try? FileManager.default.contentsOfDirectory(at: repoURL,
  175. includingPropertiesForKeys: nil,
  176. options: [.skipsHiddenFiles])
  177. else {
  178. logger.log("Failed to get repo contents \(repoURL)")
  179. return 1
  180. }
  181. for rootURL in contents {
  182. if !rootURL.hasDirectoryPath {
  183. continue
  184. }
  185. let enumerator = FileManager.default.enumerator(atPath: rootURL.path)
  186. whileLoop: while let file = enumerator?.nextObject() as? String {
  187. if let fType = enumerator?.fileAttributes?[FileAttributeKey.type] as? FileAttributeType,
  188. fType == .typeRegular {
  189. if file.starts(with: ".") {
  190. continue
  191. }
  192. if !(file.hasSuffix(".h") ||
  193. file.hasSuffix(".m") ||
  194. file.hasSuffix(".mm") ||
  195. file.hasSuffix(".c") ||
  196. file.hasSuffix(".swift")) {
  197. continue
  198. }
  199. let fullTransformPath = rootURL.path + "/" + file
  200. for dirPattern in skipDirPatterns {
  201. if fullTransformPath.range(of: dirPattern) != nil {
  202. continue whileLoop
  203. }
  204. }
  205. checkFile(
  206. fullTransformPath,
  207. logger: logger,
  208. inRepo: repoURL,
  209. isSwiftFile: file.hasSuffix(".swift")
  210. )
  211. }
  212. }
  213. }
  214. return logger.foundError ? 1 : 0
  215. }
  216. exit(main())