Skip to content

Commit

Permalink
Merge pull request #80 from JohnSundell/relative-paths
Browse files Browse the repository at this point in the history
Add API for computing a path relative to a parent folder
  • Loading branch information
JohnSundell authored Apr 5, 2019
2 parents c6d6bbd + eb96a42 commit 92b57be
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,30 @@ public class FileSystem {
self.name = pathComponents[pathComponents.count - 2]
}
}

/**
* Return this item's path relative to a given parent folder
*
* - parameter folder: The parent folder to return a relative path to
*
* - returns: Either a relative path, if the passed folder is indeed
* a parent (even if it's not a direct one) for this item. Otherwise
* the item's full path is returned.
*/
public func path(relativeTo folder: Folder) -> String {
guard path.hasPrefix(folder.path) else {
return path
}

let index = path.index(path.startIndex, offsetBy: folder.path.count)
var subpath = path[index...]

if subpath.hasSuffix("/") {
subpath.removeLast()
}

return String(subpath)
}

/**
* Rename the item
Expand Down
23 changes: 23 additions & 0 deletions Tests/FilesTests/FilesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,27 @@ class FilesTests: XCTestCase {
}
}

func testRelativePaths() {
performTest {
let file = try folder.createFile(named: "FileA")
let subfolder = try folder.createSubfolder(named: "Folder")
let fileInSubfolder = try subfolder.createFile(named: "FileB")

XCTAssertEqual(file.path(relativeTo: folder), "FileA")
XCTAssertEqual(subfolder.path(relativeTo: folder), "Folder")
XCTAssertEqual(fileInSubfolder.path(relativeTo: folder), "Folder/FileB")
}
}

func testRelativePathIsAbsolutePathForNonParent() {
performTest {
let file = try folder.createFile(named: "FileA")
let subfolder = try folder.createSubfolder(named: "Folder")

XCTAssertEqual(file.path(relativeTo: subfolder), file.path)
}
}

func testCreatingFileFromFileSystem() {
performTest {
let fileName = "three"
Expand Down Expand Up @@ -789,6 +810,8 @@ class FilesTests: XCTestCase {
("testAccessingHomeFolder", testAccessingHomeFolder),
("testAccessingCurrentWorkingDirectory", testAccessingCurrentWorkingDirectory),
("testNameExcludingExtensionWithLongFileName", testNameExcludingExtensionWithLongFileName),
("testRelativePaths", testRelativePaths),
("testRelativePathIsAbsolutePathForNonParent", testRelativePathIsAbsolutePathForNonParent),
("testCreatingFileFromFileSystem", testCreatingFileFromFileSystem),
("testCreateFileFromFileSystemIfNeeded", testCreateFileFromFileSystemIfNeeded),
("testCreatingFolderFromFileSystem", testCreatingFolderFromFileSystem),
Expand Down

0 comments on commit 92b57be

Please sign in to comment.