Paths

functions for path manipulation and information retrieval


Functions

Predicates


The Paths module provides functionality for manipulating file system paths and extracting components from paths and URLs.

Key Concepts

  • Path manipulation and normalization
  • Path component extraction
  • URL parsing
  • Path type checking
  • Relative path handling

Basic Usage

Path Components

path: "photos/vacation/beach.jpg"

; extract components
extract.directory path          ; photos/vacation
extract.filename path           ; beach
extract.extension path          ; .jpg
extract.basename path           ; beach.jpg

; check path attributes
absolute? "/Users"              ; => true
absolute? "photos/img.jpg"      ; => false

URL Components

url: "https://example.com:8080/path/page.html?q=term#section"

; extract URL parts
print extract.scheme url        ; https
print extract.host url          ; example.com
print extract.port url          ; 8080
print extract.path url          ; /path/page.html
print extract.query url         ; q=term
print extract.anchor url        ; section

Path Normalization

; normalize paths (resolve . and ..)
print normalize "./folder/../file.txt"      ; file.txt

; force treating string as file
print normalize.executable "script"         ; ./script

; expand tildes
print normalize.tilde "~/code"              ; /home/user/code

Relative Paths

; get path relative to current script
read relative "some/file.txt"           ; based on script location

; the exact same thing (and more natural-looking)
read ./"some/file.txt"

Common Patterns

Path Building

pathBuilder: function [components][
    path: "/"
    loop components 'comp [
        normalized: normalize comp
        'path ++ normalized ++ "/"
    ]
    return normalize path
]

; usage
fullPath: pathBuilder ["home" "user" "documents" "file.txt"]

print fullPath
; /home/user/documents/file.txt

URL Parsing Helper

parseUrl: function [url][
    extracted: extract url
    #[
        protocol: extracted\scheme
        domain: extracted\host
        port: extracted\port
        endpoint: extracted\path
        params: extracted\query
    ]
]

; usage
components: parseUrl "https://api.example.com:8080/v1/users?active=true"

print ["API Version:" components\endpoint]
; API Version: /v1/users 

Working with Extensions

getFileType: function [filepath][
    ext: extract.extension filepath
    case ext [
        ".txt" -> "text file"
        ".jpg" -> "image file"
        ".mp3" -> "audio file"
        ".mp4" -> "video file"
        any    -> "unknown file type"
    ]
]

; usage
print getFileType "document.txt"    ; text file

Path Checks

validatePath: function [filepath][
    p: filepath
    if not? absolute? p ->
        p: normalize relative p
    
    ensure exists? p
    ensure file? p
    
    return p
]

; usage
if error? try [
    file: validatePath "setting.cfg"
    print ["Valid file:" file]
][
    print "Invalid or missing file"
]