check_imports.swift 8.8 KB

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