check_imports.swift 8.3 KB

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