path

Join, normalize, and inspect filesystem paths.

import path

Paths use / as the separator and understand both Unix-style absolute paths (/usr/bin) and Windows drive prefixes (C:).

Building paths

path_join(left, right) → string

Join two segments with exactly one separator, collapsing any extras.

path_join("a/", "/b")
-- Output: "a/b"
path_join_many(parts) → string

Join a list of segments left to right.

path_join_many(["a", "b", "c"])
-- Output: "a/b/c"
path_split(path) → list

Split a path into its non-empty segments.

path_split("/usr/local/bin")
-- Output: ["usr", "local", "bin"]
path_sep() → string

The path separator used by the library.

path_sep()
-- Output: "/"

Inspection

path_is_absolute(path) → boolean

Whether the path is absolute (leading / or a drive prefix).

path_is_absolute("/etc/hosts")
-- Output: true
path_is_absolute("docs/api")
-- Output: false
path_basename(path) → string

The final segment of the path.

path_basename("/usr/local/bin/bern")
-- Output: "bern"
path_dirname(path) → string

The parent directory.

path_dirname("/usr/local/bin/bern")
-- Output: "/usr/local/bin"
path_extname(path) → string

The extension including the leading dot, or "" when there is none.

path_extname("archive.tar.gz")
-- Output: ".gz"
path_stem(path) → string

The basename without its extension.

path_stem("report.pdf")
-- Output: "report"

Normalization

path_normalize(path) → string

Resolve redundant separators and the . / .. segments.

path_normalize("a/./b/../c")
-- Output: "a/c"

path_normalize("/a//b/../c")
-- Output: "/a/c"

Putting it together

The functions combine to rewrite a path safely - here we move a file into a sibling directory while keeping its name:

Relocating a file next to its source

import path

source = "/projects/bern/src/main.brn"

dir  = path_dirname(source)
-- "/projects/bern/src"
name = path_basename(source)
-- "main.brn"

dest = path_normalize(path_join_many([dir, "..", "build", name]))
-- Output: "/projects/bern/build/main.brn"

And deriving an output filename by swapping the extension via path_stem:

Choosing an output name

import path

def with_ext(file, ext) -> path_join(path_dirname(file), path_stem(file) + ext)

with_ext("docs/notes.md", ".html")
-- Output: "docs/notes.html"