check_imports.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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/", "FirebaseStorage/Tests/Integration",
  24. "FirebaseDynamicLinks/Tests/Integration",
  25. "FirebaseInAppMessaging/Tests/Integration/",
  26. "SymbolCollisionTest/", "/gen/",
  27. "CocoapodsIntegrationTest/", "FirebasePerformance/Tests/TestApp/",
  28. "cmake-build-debug/", "build/",
  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. "FirebaseAppDistribution",
  37. "FirebaseCore/Sources/Private", // TODO: work through adding this back.
  38. "Firebase/CoreDiagnostics",
  39. "FirebaseDatabase/Sources/third_party/Wrap-leveldb", // Pending SwiftPM for leveldb.
  40. "Example",
  41. "FirebaseInstallations/Source/Tests/Unit/",
  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. 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. let isPublic = file.range(of: "/Public/") != nil &&
  72. // TODO: Skip legacy GDTCCTLibrary file that isn't Public and should be moved.
  73. file.range(of: "GDTCCTLibrary/Public/GDTCOREvent+GDTCCTSupport.h") == nil
  74. let isPrivate = file.range(of: "/Sources/Private/") != nil ||
  75. // Delete when FirebaseInstallations fixes directory structure.
  76. file.range(of: "Source/Library/Private/FirebaseInstallationsInternal.h") != nil ||
  77. file.range(of: "GDTCORLibrary/Internal/GoogleDataTransportInternal.h") != nil
  78. // Treat all files with names finishing on "Test" or "Tests" as files with tests.
  79. let isTestFile = file.contains("Test.m") || file.contains("Tests.m") ||
  80. file.contains("Test.swift") || file.contains("Tests.swift")
  81. let isBridgingHeader = file.contains("Bridging-Header.h")
  82. var inSwiftPackage = false
  83. var inSwiftPackageElse = false
  84. let lines = fileContents.components(separatedBy: .newlines)
  85. var lineNum = 0
  86. nextLine: for rawLine in lines {
  87. let line = rawLine.trimmingCharacters(in: .whitespaces)
  88. lineNum += 1
  89. if line.starts(with: "#if SWIFT_PACKAGE") {
  90. inSwiftPackage = true
  91. } else if inSwiftPackage, line.starts(with: "#else") {
  92. inSwiftPackage = false
  93. inSwiftPackageElse = true
  94. } else if inSwiftPackageElse, line.starts(with: "#endif") {
  95. inSwiftPackageElse = false
  96. } else if inSwiftPackage {
  97. continue
  98. } else if file.contains("FirebaseTestingSupport") {
  99. // Module imports ok in SPM only test infrastructure.
  100. continue
  101. } else if line.starts(with: "@import") {
  102. // "@import" is only allowed for Swift Package Manager.
  103. logger.importLog("@import should not be used in CocoaPods library code", file, lineNum)
  104. }
  105. // "The #else of a SWIFT_PACKAGE check should only do CocoaPods module-style imports."
  106. if line.starts(with: "#import") || line.starts(with: "#include") {
  107. let importFile = line.components(separatedBy: " ")[1]
  108. if inSwiftPackageElse {
  109. if importFile.first != "<" {
  110. logger
  111. .importLog("Import in SWIFT_PACKAGE #else should start with \"<\".", file, lineNum)
  112. }
  113. continue
  114. }
  115. let importFileRaw = importFile.replacingOccurrences(of: "\"", with: "")
  116. .replacingOccurrences(of: "<", with: "")
  117. .replacingOccurrences(of: ">", with: "")
  118. if importFile.first == "\"" {
  119. // Public Headers should only use simple file names without paths.
  120. if isPublic {
  121. if importFile.contains("/") {
  122. logger.importLog("Public header import should not include \"/\"", file, lineNum)
  123. }
  124. } else if !FileManager.default.fileExists(atPath: repoURL.path + "/" + importFileRaw) {
  125. // Non-public header imports should be repo-relative paths. Unqualified imports are
  126. // allowed in private headers.
  127. if !isPrivate || importFile.contains("/") {
  128. for skip in skipImportPatterns {
  129. if importFileRaw.starts(with: skip) {
  130. continue nextLine
  131. }
  132. }
  133. logger.importLog("Import \(importFileRaw) does not exist.", file, lineNum)
  134. }
  135. }
  136. } else if importFile.first == "<", !isPrivate, !isTestFile, !isBridgingHeader, !isPublic {
  137. // Verify that double quotes are always used for intra-module imports.
  138. if importFileRaw.starts(with: "Firebase") {
  139. logger
  140. .importLog("Imports internal to the repo should use double quotes not \"<\"", file,
  141. lineNum)
  142. }
  143. }
  144. }
  145. }
  146. }
  147. private func main() -> Int32 {
  148. let logger = ErrorLogger()
  149. // Search the path upwards to find the root of the firebase-ios-sdk repo.
  150. var url = URL(fileURLWithPath: FileManager().currentDirectoryPath)
  151. while url.path != "/" {
  152. let script = url.appendingPathComponent("scripts/check_imports.swift")
  153. if FileManager.default.fileExists(atPath: script.path) {
  154. break
  155. }
  156. url = url.deletingLastPathComponent()
  157. }
  158. let repoURL = url
  159. guard let contents = try? FileManager.default.contentsOfDirectory(at: repoURL,
  160. includingPropertiesForKeys: nil,
  161. options: [.skipsHiddenFiles])
  162. else {
  163. logger.log("Failed to get repo contents \(repoURL)")
  164. return 1
  165. }
  166. for rootURL in contents {
  167. if !rootURL.hasDirectoryPath {
  168. continue
  169. }
  170. let enumerator = FileManager.default.enumerator(atPath: rootURL.path)
  171. whileLoop: while let file = enumerator?.nextObject() as? String {
  172. if let fType = enumerator?.fileAttributes?[FileAttributeKey.type] as? FileAttributeType,
  173. fType == .typeRegular {
  174. if file.starts(with: ".") {
  175. continue
  176. }
  177. if !(file.hasSuffix(".h") ||
  178. file.hasSuffix(".m") ||
  179. file.hasSuffix(".mm") ||
  180. file.hasSuffix(".c")) {
  181. continue
  182. }
  183. let fullTransformPath = rootURL.path + "/" + file
  184. for dirPattern in skipDirPatterns {
  185. if fullTransformPath.range(of: dirPattern) != nil {
  186. continue whileLoop
  187. }
  188. }
  189. checkFile(fullTransformPath, logger: logger, inRepo: repoURL)
  190. }
  191. }
  192. }
  193. return logger.foundError ? 1 : 0
  194. }
  195. exit(main())