Skip to content

Commit

Permalink
Add API to create a file with string content
Browse files Browse the repository at this point in the history
This change adds a convenience API to create a new file
with content based on a string, which is a quite common
operation.
  • Loading branch information
JohnSundell committed Jul 10, 2017
1 parent 948f4b5 commit 0077f7a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,23 @@ public final class Folder: FileSystem.Item, FileSystemIterable {
return try File(path: filePath, using: fileManager)
}

/**
* Create a file in this folder and return it
*
* - parameter fileName: The name of the file to create
* - parameter contents: The string content that the file should contain
* - parameter encoding: The encoding that the given string content should be encoded with
*
* - throws: `File.Error.writeFailed` if the file couldn't be created
*
* - returns: The file that was created
*/
@discardableResult public func createFile(named fileName: String, contents: String, encoding: String.Encoding = .utf8) throws -> File {
let file = try createFile(named: fileName)
try file.write(string: contents, encoding: encoding)
return file
}

/**
* Either return an existing file, or create a new one, for a given name
*
Expand Down
7 changes: 7 additions & 0 deletions Tests/FilesTests/FilesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,13 @@ class FilesTests: XCTestCase {
}
}

func testCreatingFileWithString() {
performTest {
let file = try folder.createFile(named: "file", contents: "Hello world")
XCTAssertEqual(try file.readAsString(), "Hello world")
}
}

func testUsingCustomFileManager() {
class FileManagerMock: FileManager {
var noFilesExist = false
Expand Down

0 comments on commit 0077f7a

Please sign in to comment.