String+FileKit.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // String+FileKit.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. var ReadableWritableStringEncoding = String.Encoding.utf8
  29. /// Allows String to be used as a ReadableWritable.
  30. extension String: ReadableWritable {
  31. /// Creates a string from a path.
  32. public static func read(from path: Path) throws -> String {
  33. do {
  34. return try String(contentsOfFile: path._safeRawValue,
  35. encoding: ReadableWritableStringEncoding)
  36. } catch {
  37. throw FileKitError.readFromFileFail(path: path, error: error)
  38. }
  39. }
  40. /// Writes the string to a path atomically.
  41. ///
  42. /// - Parameter path: The path being written to.
  43. ///
  44. public func write(to path: Path) throws {
  45. try write(to: path, atomically: true)
  46. }
  47. /// Writes the string to a path with `ReadableWritableStringEncoding` encoding.
  48. ///
  49. /// - Parameter path: The path being written to.
  50. /// - Parameter useAuxiliaryFile: If `true`, the data is written to an
  51. /// auxiliary file that is then renamed to the
  52. /// file. If `false`, the data is written to
  53. /// the file directly.
  54. ///
  55. public func write(to path: Path, atomically useAuxiliaryFile: Bool) throws {
  56. do {
  57. try self.write(toFile: path._safeRawValue,
  58. atomically: useAuxiliaryFile,
  59. encoding: ReadableWritableStringEncoding)
  60. } catch {
  61. throw FileKitError.writeToFileFail(path: path, error: error)
  62. }
  63. }
  64. }