check_imports.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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/master/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. "FirebaseAuth/",
  27. // TODO: Turn Combine back on without Auth includes.
  28. "FirebaseCombineSwift/Tests/Unit/FirebaseCombine-unit-Bridging-Header.h",
  29. "SymbolCollisionTest/", "/gen/",
  30. "CocoapodsIntegrationTest/", "FirebasePerformance/Tests/TestApp/",
  31. "cmake-build-debug/", "build/", "ObjCIntegration/",
  32. "FirebasePerformance/Tests/FIRPerfE2E/"] +
  33. [
  34. "CoreOnly/Sources", // Skip Firebase.h.
  35. "SwiftPMTests", // The SwiftPM imports test module imports.
  36. "FirebaseSessions/Protogen/", // Generated nanopb code with imports
  37. ] +
  38. // The following are temporary skips pending working through a first pass of the repo:
  39. [
  40. "FirebaseDatabase/Sources/third_party/Wrap-leveldb", // Pending SwiftPM for leveldb.
  41. "Example",
  42. "Firestore",
  43. "GoogleUtilitiesComponents",
  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 `@_implementationOnly 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/Extension") != nil
  94. // Treat all files with names finishing on "Test" or "Tests" as files with tests.
  95. let isTestFile = file.contains("Test.m") || file.contains("Tests.m") ||
  96. file.contains("Test.swift") || file.contains("Tests.swift")
  97. let isBridgingHeader = file.contains("Bridging-Header.h")
  98. var inSwiftPackage = false
  99. var inSwiftPackageElse = false
  100. let lines = fileContents.components(separatedBy: .newlines)
  101. var lineNum = 0
  102. nextLine: for rawLine in lines {
  103. let line = rawLine.trimmingCharacters(in: .whitespaces)
  104. lineNum += 1
  105. if line.starts(with: "#if SWIFT_PACKAGE") {
  106. inSwiftPackage = true
  107. } else if inSwiftPackage, line.starts(with: "#else") {
  108. inSwiftPackage = false
  109. inSwiftPackageElse = true
  110. } else if inSwiftPackageElse, line.starts(with: "#endif") {
  111. inSwiftPackageElse = false
  112. } else if inSwiftPackage {
  113. continue
  114. } else if file.contains("FirebaseTestingSupport") {
  115. // Module imports ok in SPM only test infrastructure.
  116. continue
  117. }
  118. // "The #else of a SWIFT_PACKAGE check should only do CocoaPods module-style imports."
  119. if line.starts(with: "#import") || line.starts(with: "#include") {
  120. let importFile = line.components(separatedBy: " ")[1]
  121. if inSwiftPackageElse {
  122. if importFile.first != "<" {
  123. logger
  124. .importLog("Import in SWIFT_PACKAGE #else should start with \"<\".", file, lineNum)
  125. }
  126. continue
  127. }
  128. let importFileRaw = importFile.replacingOccurrences(of: "\"", with: "")
  129. .replacingOccurrences(of: "<", with: "")
  130. .replacingOccurrences(of: ">", with: "")
  131. if importFile.first == "\"" {
  132. // Public Headers should only use simple file names without paths.
  133. if isPublic {
  134. if importFile.contains("/") {
  135. logger.importLog("Public header import should not include \"/\"", file, lineNum)
  136. }
  137. } else if !FileManager.default.fileExists(atPath: repoURL.path + "/" + importFileRaw) {
  138. // Non-public header imports should be repo-relative paths. Unqualified imports are
  139. // allowed in private headers.
  140. if !isPrivate || importFile.contains("/") {
  141. for skip in skipImportPatterns {
  142. if importFileRaw.starts(with: skip) {
  143. continue nextLine
  144. }
  145. }
  146. logger.importLog("Import \(importFileRaw) does not exist.", file, lineNum)
  147. }
  148. }
  149. } else if importFile.first == "<", !isPrivate, !isTestFile, !isBridgingHeader, !isPublic {
  150. // Verify that double quotes are always used for intra-module imports.
  151. if importFileRaw.starts(with: "Firebase") {
  152. logger
  153. .importLog("Imports internal to the repo should use double quotes not \"<\"", file,
  154. lineNum)
  155. }
  156. }
  157. }
  158. }
  159. }
  160. private func main() -> Int32 {
  161. let logger = ErrorLogger()
  162. // Search the path upwards to find the root of the firebase-ios-sdk repo.
  163. var url = URL(fileURLWithPath: FileManager().currentDirectoryPath)
  164. while url.path != "/" {
  165. let script = url.appendingPathComponent("scripts/check_imports.swift")
  166. if FileManager.default.fileExists(atPath: script.path) {
  167. break
  168. }
  169. url = url.deletingLastPathComponent()
  170. }
  171. let repoURL = url
  172. guard let contents = try? FileManager.default.contentsOfDirectory(at: repoURL,
  173. includingPropertiesForKeys: nil,
  174. options: [.skipsHiddenFiles])
  175. else {
  176. logger.log("Failed to get repo contents \(repoURL)")
  177. return 1
  178. }
  179. for rootURL in contents {
  180. if !rootURL.hasDirectoryPath {
  181. continue
  182. }
  183. let enumerator = FileManager.default.enumerator(atPath: rootURL.path)
  184. whileLoop: while let file = enumerator?.nextObject() as? String {
  185. if let fType = enumerator?.fileAttributes?[FileAttributeKey.type] as? FileAttributeType,
  186. fType == .typeRegular {
  187. if file.starts(with: ".") {
  188. continue
  189. }
  190. if !(file.hasSuffix(".h") ||
  191. file.hasSuffix(".m") ||
  192. file.hasSuffix(".mm") ||
  193. file.hasSuffix(".c") ||
  194. file.hasSuffix(".swift")) {
  195. continue
  196. }
  197. let fullTransformPath = rootURL.path + "/" + file
  198. for dirPattern in skipDirPatterns {
  199. if fullTransformPath.range(of: dirPattern) != nil {
  200. continue whileLoop
  201. }
  202. }
  203. checkFile(
  204. fullTransformPath,
  205. logger: logger,
  206. inRepo: repoURL,
  207. isSwiftFile: file.hasSuffix(".swift")
  208. )
  209. }
  210. }
  211. }
  212. return logger.foundError ? 1 : 0
  213. }
  214. exit(main())