check_imports.swift 7.5 KB

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