check_imports.swift 8.2 KB

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