Advertisement
marcusziade

delete file headers for swift files

Jan 25th, 2023 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.45 KB | None | 0 0
  1. import Foundation
  2.  
  3. enum FileManagerError: Error { case directoryNotFound }
  4.  
  5. let directory = "path obscured"
  6. let fileManager = FileManager.default
  7.  
  8. do {
  9.     try processFiles()
  10. } catch {
  11.     print("Error while processing files: \(error)")
  12. }
  13.  
  14. func processFiles() throws {
  15.     guard let files = try? fileManager.contentsOfDirectory(atPath: directory) else {
  16.         throw FileManagerError.directoryNotFound
  17.     }
  18.     let swiftFiles = files.filter { $0.hasSuffix(".swift") }
  19.     for file in swiftFiles {
  20.         let fileURL = URL(fileURLWithPath: directory, isDirectory: false).appendingPathComponent(file)
  21.         try stripHeaders(fileURL: fileURL)
  22.     }
  23. }
  24.  
  25. private func stripHeaders(fileURL: URL) throws {
  26.     var inHeader = true
  27.     var lines: [String] = []
  28.     do {
  29.         let fileContent = try String(contentsOf: fileURL)
  30.         lines = fileContent.components(separatedBy: .newlines)
  31.         var newContent = ""
  32.         for line in lines {
  33.             if inHeader && line.hasPrefix("//") && !line.contains("swift-tools-version") {
  34.                 continue
  35.             } else if inHeader && !line.hasPrefix("//") {
  36.                 if line.isEmpty {
  37.                     continue
  38.                 } else {
  39.                     inHeader = false
  40.                 }
  41.             }
  42.             newContent += line + "\n"
  43.         }
  44.         try newContent.write(to: fileURL, atomically: true, encoding: .utf8)
  45.     } catch {
  46.         throw error
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement