Add rename

This commit is contained in:
Max Howell
2019-01-31 08:38:00 -05:00
parent eb34ac4af8
commit c6e840b9b6
3 changed files with 44 additions and 5 deletions

View File

@@ -174,6 +174,13 @@ public extension Path {
} }
return self return self
} }
@discardableResult
func rename(_ newname: String) throws -> Path {
let newpath = parent/newname
try FileManager.default.moveItem(atPath: string, toPath: newpath.string)
return newpath
}
} }
/// Options for `Path.mkdir(_:)` /// Options for `Path.mkdir(_:)`

View File

@@ -165,12 +165,42 @@ class PathTests: XCTestCase {
} }
func testCopyInto() throws { func testCopyInto() throws {
try Path.mktemp { root1 in
let bar1 = try root1.join("bar").touch()
try Path.mktemp { root2 in
let bar2 = try root2.join("bar").touch()
XCTAssertThrowsError(try bar1.copy(into: root2))
try bar1.copy(into: root2, overwrite: true)
XCTAssertTrue(bar1.exists)
XCTAssertTrue(bar2.exists)
}
}
}
func testMoveInto() throws {
try Path.mktemp { root1 in
let bar1 = try root1.join("bar").touch()
try Path.mktemp { root2 in
let bar2 = try root2.join("bar").touch()
XCTAssertThrowsError(try bar1.move(into: root2))
try bar1.move(into: root2, overwrite: true)
XCTAssertFalse(bar1.exists)
XCTAssertTrue(bar2.exists)
}
}
}
func testRename() throws {
try Path.mktemp { root in try Path.mktemp { root in
let bar = try root.join("bar").touch() do {
try Path.mktemp { root in let file = try root.bar.touch()
try root.join("bar").touch() let foo = try file.rename("foo")
XCTAssertThrowsError(try bar.copy(into: root)) XCTAssertFalse(file.exists)
try bar.copy(into: root, overwrite: true) XCTAssertTrue(foo.isFile)
}
do {
let file = try root.bar.touch()
XCTAssertThrowsError(try file.rename("foo"))
} }
} }
} }

View File

@@ -15,8 +15,10 @@ extension PathTests {
("testJoin", testJoin), ("testJoin", testJoin),
("testMkpathIfExists", testMkpathIfExists), ("testMkpathIfExists", testMkpathIfExists),
("testMktemp", testMktemp), ("testMktemp", testMktemp),
("testMoveInto", testMoveInto),
("testRelativePathCodable", testRelativePathCodable), ("testRelativePathCodable", testRelativePathCodable),
("testRelativeTo", testRelativeTo), ("testRelativeTo", testRelativeTo),
("testRename", testRename),
] ]
} }