diff --git a/lib/chibi/pathname.scm b/lib/chibi/pathname.scm index 5fae8f11..347ac51d 100644 --- a/lib/chibi/pathname.scm +++ b/lib/chibi/pathname.scm @@ -76,6 +76,13 @@ (define (path-replace-extension path ext) (string-append (path-strip-extension path) "." ext)) +;;> Returns \var{path} with any leading ../ removed. + +(define (path-strip-leading-parents path) + (if (string-prefix? "../" path) + (path-strip-leading-parents (substring path 3)) + (if (equal? path "..") "" path))) + ;;> Returns \scheme{#t} iff \var{path} is an absolute path, ;;> i.e. begins with "/". diff --git a/lib/chibi/pathname.sld b/lib/chibi/pathname.sld index 016cf7fe..8f7aaaf8 100644 --- a/lib/chibi/pathname.sld +++ b/lib/chibi/pathname.sld @@ -2,7 +2,7 @@ (define-library (chibi pathname) (export path-strip-directory path-directory path-extension path-strip-extension path-replace-extension - path-absolute? path-relative? + path-absolute? path-relative? path-strip-leading-parents path-relative-to path-normalize make-path) (import (chibi) (chibi string)) (include "pathname.scm")) diff --git a/tests/path-tests.scm b/tests/path-tests.scm index d6f30654..182f8702 100644 --- a/tests/path-tests.scm +++ b/tests/path-tests.scm @@ -172,6 +172,13 @@ (test "../.." (path-normalize "a/b/c/../../../../..")) (test "../../.." (path-normalize "../a/b/c/../../../../..")) +(test "" (path-strip-leading-parents "..")) +(test "" (path-strip-leading-parents "../")) +(test "a" (path-strip-leading-parents "../a")) +(test "a/b" (path-strip-leading-parents "../../a/b")) +(test "a/b" (path-strip-leading-parents "../../../a/b")) +(test "a/../b" (path-strip-leading-parents "../../../a/../b")) + (test "path-relative-to" "c" (path-relative-to "/a/b/c" "/a/b")) (test "c" (path-relative-to "/a/b/c" "/a/b/")) (test "." (path-relative-to "/a/b/" "/a/b/"))