Skip to content

Commit

Permalink
new os.isRelativeTo (nim-lang#13212)
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour authored and Araq committed Jan 22, 2020
1 parent 3e843ab commit 7356bc2
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
Eg: `echo ?.n.typ.kind`
- Added `minIndex` and `maxIndex` to the `sequtils` module

- Added `os.isRelativeTo` to tell whether a path is relative to another

## Library changes

- `asyncdispatch.drain` now properly takes into account `selector.hasPendingOperations`
Expand Down
12 changes: 12 additions & 0 deletions lib/pure/os.nim
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,18 @@ proc relativePath*(path, base: string; sep = DirSep): string {.
if not f.hasNext(path): break
ff = f.next(path)

proc isRelativeTo*(path: string, base: string): bool {.since: (1, 1).} =
## Returns true if `path` is relative to `base`.
runnableExamples:
doAssert isRelativeTo("./foo//bar", "foo")
doAssert isRelativeTo("foo/bar", ".")
doAssert isRelativeTo("/foo/bar.nim", "/foo/bar.nim")
doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
let path = path.normalizePath
let base = base.normalizePath
let ret = relativePath(path, base)
result = path.len > 0 and not ret.startsWith ".."

proc parentDirPos(path: string): int =
var q = 1
if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2
Expand Down
12 changes: 12 additions & 0 deletions tests/stdlib/tos.nim
Original file line number Diff line number Diff line change
Expand Up @@ -382,3 +382,15 @@ block osenv:
doAssert existsEnv(dummyEnvVar) == false
delEnv(dummyEnvVar) # deleting an already deleted env var
doAssert existsEnv(dummyEnvVar) == false

block isRelativeTo:
doAssert isRelativeTo("/foo", "/")
doAssert isRelativeTo("/foo/bar", "/foo")
doAssert isRelativeTo("foo/bar", "foo")
doAssert isRelativeTo("/foo/bar.nim", "/foo/bar.nim")
doAssert isRelativeTo("./foo/", "foo")
doAssert isRelativeTo("foo", "./foo/")
doAssert isRelativeTo(".", ".")
doAssert isRelativeTo("foo/bar", ".")
doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
doAssert not isRelativeTo("/foo2", "/foo")

0 comments on commit 7356bc2

Please sign in to comment.