TextFile.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //
  2. // TextFile.swift
  3. // FileKit
  4. //
  5. // The MIT License (MIT)
  6. //
  7. // Copyright (c) 2015-2017 Nikolai Vazquez
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. //
  27. import Foundation
  28. /// A representation of a filesystem text file.
  29. ///
  30. /// The data type is String.
  31. open class TextFile: File<String> {
  32. /// The text file's string encoding.
  33. open var encoding: String.Encoding
  34. /// Initializes a text file from a path.
  35. ///
  36. /// - Parameter path: The path to be created a text file from.
  37. public override init(path: Path) {
  38. self.encoding = String.Encoding.utf8
  39. super.init(path: path)
  40. }
  41. /// Initializes a text file from a path with an encoding.
  42. ///
  43. /// - Parameter path: The path to be created a text file from.
  44. /// - Parameter encoding: The encoding to be used for the text file.
  45. public init(path: Path, encoding: String.Encoding) {
  46. self.encoding = encoding
  47. super.init(path: path)
  48. }
  49. /// Writes a string to a text file using the file's encoding.
  50. ///
  51. /// - Parameter data: The string to be written to the text file.
  52. /// - Parameter useAuxiliaryFile: If `true`, the data is written to an
  53. /// auxiliary file that is then renamed to the
  54. /// file. If `false`, the data is written to
  55. /// the file directly.
  56. ///
  57. /// - Throws: `FileKitError.WriteToFileFail`
  58. ///
  59. open override func write(_ data: String, atomically useAuxiliaryFile: Bool) throws {
  60. do {
  61. try data.write(toFile: path._safeRawValue, atomically: useAuxiliaryFile, encoding: encoding)
  62. } catch {
  63. throw FileKitError.writeToFileFail(path: path, error: error)
  64. }
  65. }
  66. }
  67. // MARK: Line Reader
  68. extension TextFile {
  69. /// Provide a reader to read line by line.
  70. ///
  71. /// - Parameter delimiter: the line delimiter (default: \n)
  72. /// - Parameter chunkSize: size of buffer (default: 4096)
  73. ///
  74. /// - Returns: the `TextFileStreamReader`
  75. ///
  76. /// - Throws:
  77. /// `FileKitError.readFromFileFail`
  78. public func streamReader(_ delimiter: String = "\n",
  79. chunkSize: Int = 4096) throws -> TextFileStreamReader {
  80. return try TextFileStreamReader(
  81. path: self.path,
  82. delimiter: delimiter,
  83. encoding: encoding,
  84. chunkSize: chunkSize
  85. )
  86. }
  87. /// Read file and return filtered lines.
  88. ///
  89. /// - Parameter motif: the motif to compare
  90. /// - Parameter include: check if line include motif if true, exclude if not (default: true)
  91. /// - Parameter options: optional options for string comparaison
  92. ///
  93. /// - Returns: the lines
  94. public func grep(_ motif: String, include: Bool = true,
  95. options: String.CompareOptions = []) -> [String] {
  96. guard let reader = try? streamReader() else {
  97. return []
  98. }
  99. defer {
  100. reader.close()
  101. }
  102. return reader.filter {($0.range(of: motif, options: options) != nil) == include }
  103. }
  104. }
  105. /// A class to read or write `TextFile`.
  106. open class TextFileStream {
  107. /// The text encoding.
  108. public let encoding: String.Encoding
  109. let delimData: Data
  110. var fileHandle: FileHandle?
  111. // MARK: - Initialization
  112. public init(
  113. fileHandle: FileHandle,
  114. delimiter: Data,
  115. encoding: String.Encoding = .utf8
  116. ) throws {
  117. self.encoding = encoding
  118. self.fileHandle = fileHandle
  119. self.delimData = delimiter
  120. }
  121. // MARK: - Deinitialization
  122. deinit {
  123. self.close()
  124. }
  125. // MARK: - public methods
  126. open var offset: UInt64 {
  127. return fileHandle?.offsetInFile ?? 0
  128. }
  129. open func seek(toFileOffset offset: UInt64) {
  130. fileHandle?.seek(toFileOffset: offset)
  131. }
  132. /// Close the underlying file. No reading must be done after calling this method.
  133. open func close() {
  134. fileHandle?.closeFile()
  135. fileHandle = nil
  136. }
  137. /// Return true if file handle closed.
  138. open var isClosed: Bool {
  139. return fileHandle == nil
  140. }
  141. }
  142. /// A class to read `TextFile` line by line.
  143. open class TextFileStreamReader: TextFileStream {
  144. /// The chunk size when reading.
  145. public let chunkSize: Int
  146. /// Tells if the position is at the end of file.
  147. open var atEOF: Bool = false
  148. var buffer: Data!
  149. // MARK: - Initialization
  150. /// - Parameter path: the file path
  151. /// - Parameter delimiter: the line delimiter (default: \n)
  152. /// - Parameter encoding: file encoding (default: .utf8)
  153. /// - Parameter chunkSize: size of buffer (default: 4096)
  154. public init(
  155. path: Path,
  156. delimiter: String = "\n",
  157. encoding: String.Encoding = .utf8,
  158. chunkSize: Int = 4096
  159. ) throws {
  160. self.chunkSize = chunkSize
  161. let fileHandle = try path.fileHandle(for: .read)
  162. self.buffer = Data(capacity: chunkSize)
  163. guard let delimData = delimiter.data(using: encoding) else {
  164. throw FileKitError.ReasonError.encoding(encoding, data: delimiter)
  165. }
  166. try super.init(fileHandle: fileHandle, delimiter: delimData, encoding: encoding)
  167. }
  168. // MARK: - public methods
  169. /// - Returns: The next line, or nil on EOF.
  170. open func nextLine() -> String? {
  171. if atEOF {
  172. return nil
  173. }
  174. // Read data chunks from file until a line delimiter is found.
  175. var range = buffer.range(of: delimData, options: [], in: 0..<buffer.count)
  176. while range == nil {
  177. guard let tmpData = fileHandle?.readData(ofLength: chunkSize), !tmpData.isEmpty else {
  178. // EOF or read error.
  179. atEOF = true
  180. if !buffer.isEmpty {
  181. // Buffer contains last line in file (not terminated by delimiter).
  182. let line = String(data: buffer, encoding: encoding)
  183. buffer.count = 0
  184. return line
  185. }
  186. // No more lines.
  187. return nil
  188. }
  189. buffer.append(tmpData)
  190. range = buffer.range(of: delimData, options: [], in: 0..<buffer.count)
  191. }
  192. // Convert complete line (excluding the delimiter) to a string.
  193. let line = String(data: buffer.subdata(in: 0..<range!.lowerBound), encoding: encoding)
  194. // Remove line (and the delimiter) from the buffer.
  195. let cleaningRange: Range<Data.Index> = 0..<range!.upperBound
  196. buffer.replaceSubrange(cleaningRange, with: Data())
  197. return line
  198. }
  199. /// Start reading from the beginning of file.
  200. open func rewind() {
  201. fileHandle?.seek(toFileOffset: 0)
  202. buffer.count = 0
  203. atEOF = false
  204. }
  205. }
  206. // Implement `SequenceType` for `TextFileStreamReader`
  207. extension TextFileStreamReader: Sequence {
  208. /// - Returns: An iterator to be used for iterating over a `TextFileStreamReader` object.
  209. public func makeIterator() -> AnyIterator<String> {
  210. return AnyIterator {
  211. return self.nextLine()
  212. }
  213. }
  214. }
  215. // MARK: Line Writer
  216. /// A class to write a `TextFile` line by line.
  217. open class TextFileStreamWriter: TextFileStream {
  218. public let append: Bool
  219. // MARK: - Initialization
  220. /// - Parameter path: the file path
  221. /// - Parameter delimiter: the line delimiter (default: \n)
  222. /// - Parameter encoding: file encoding (default: .utf8)
  223. /// - Parameter append: if true append at file end (default: false)
  224. /// - Parameter createIfNotExist: if true create file if not exixt (default: true)
  225. public init(
  226. path: Path,
  227. delimiter: String = "\n",
  228. encoding: String.Encoding = .utf8,
  229. append: Bool = false,
  230. createIfNotExist: Bool = true
  231. ) throws {
  232. if createIfNotExist && !path.exists {
  233. try path.createFile()
  234. }
  235. self.append = append
  236. let fileHandle = try path.fileHandle(for: .write)
  237. if append {
  238. fileHandle.seekToEndOfFile()
  239. }
  240. guard let delimData = delimiter.data(using: encoding) else {
  241. throw FileKitError.ReasonError.encoding(encoding, data: delimiter)
  242. }
  243. try super.init(fileHandle: fileHandle, delimiter: delimData, encoding: encoding)
  244. }
  245. /// Write a new line in file
  246. /// - Parameter line: the line
  247. /// - Parameter delim: append the delimiter (default: true)
  248. ///
  249. /// - Returns: true if successfully.
  250. @discardableResult
  251. open func write(line: String, delim: Bool = true) -> Bool {
  252. if let handle = fileHandle, let data = line.data(using: self.encoding) {
  253. handle.write(data)
  254. if delim {
  255. handle.write(delimData)
  256. }
  257. return true
  258. }
  259. return false
  260. }
  261. /// Write a line delimiter.
  262. ///
  263. /// - Returns: true if successfully.
  264. open func writeDelimiter() -> Bool {
  265. if let handle = fileHandle {
  266. handle.write(delimData)
  267. return true
  268. }
  269. return false
  270. }
  271. /// Causes all in-memory data and attributes of the file represented by the receiver to be written to permanent storage.
  272. open func synchronize() {
  273. fileHandle?.synchronizeFile()
  274. }
  275. }
  276. extension TextFile {
  277. /// Provide a writer to write line by line.
  278. ///
  279. /// - Parameter delimiter: the line delimiter (default: \n)
  280. /// - Parameter append: if true append at file end (default: false)
  281. ///
  282. /// - Returns: the `TextFileStreamWriter`
  283. ///
  284. /// - Throws:
  285. /// `FileKitError.CreateFileFail`,
  286. /// `FileKitError.writeToFileFail`
  287. public func streamWriter(_ delimiter: String = "\n", append: Bool = false) throws -> TextFileStreamWriter {
  288. return try TextFileStreamWriter(
  289. path: self.path,
  290. delimiter: delimiter,
  291. encoding: encoding,
  292. append: append
  293. )
  294. }
  295. }