Tern

path

The path module works with file paths as text: joining, cleaning, taking them apart, extensions, relative paths, and shell-style patterns. Paths use /, as on Linux, macOS and WebAssembly. Only path.abs (which reads the working directory) and path.glob (which lists directories) look at the disk; everything else is string work, the same as Go's path.

import path

fn main():
    p = path.join("assets", "img/logo.png")
    print(p, path.dir(p), path.base(p), path.ext(p), path.stem(p))
    print(path.with_ext(p, ".webp"))
    print(path.clean("a//b/./c/../d/"))
    print(path.rel("/srv/app", "/srv/app/static/x.css"))
    print(path.matches("*.tn", "main.tn"), path.parts("/usr/local/bin"))
Output
assets/img/logo.png assets/img logo.png .png logo
assets/img/logo.webp
a/b/d
Ok("static/x.css")
true ["/", "usr", "local", "bin"]

Functions

fn join(a: str, b: str) str          a and b with one "/" between, cleaned; "" parts are skipped
fn join_all(parts: [str]) str        the same for any number of parts
fn resolve(base: str, p: str) str    p if it's absolute, else join(base, p)
fn clean(p: str) str                 the shortest path naming the same file, by text alone
fn dir(p: str) str                   everything before the last name, cleaned
fn base(p: str) str                  the last name (a trailing "/" is ignored)
fn split(p: str) (str, str)          (up to and including the last "/", the rest)
fn ext(p: str) str                   the last name's extension, with its dot ("" if none)
fn stem(p: str) str                  the last name without its extension
fn with_ext(p: str, ext: str) str    p with its extension replaced, added, or (ext "") removed
fn parts(p: str) [str]               the names in clean(p), "/" first for an absolute path
fn is_abs(p: str) bool               starts with "/"
fn abs(p: str) str                   resolve(os.cwd(), p)
fn rel(base: str, target: str) Result[str, str]   a path to target from base
fn matches(pattern: str, name: str) bool          shell-style pattern match
fn glob(pattern: str) [str]          the existing files and directories that match, sorted

Joining

join puts one / between its parts and cleans the result. Like Go's filepath.Join, an absolute second part does not start over: join("/a", "/b") is /a/b. When the second part may be absolute and should win (a path from a config file, relative to the config's directory unless it's absolute), use resolve, which works like Python's os.path.join:

import path

fn main():
    print(path.join("/a", "/b"), path.resolve("/a", "/b"), path.resolve("/a", "b"))
    print(path.join("", "x"), path.join_all(["a", "", "b/", "../c"]))
Output
/a/b /b /a/b
x a/c

Cleaning

clean applies Go's rules by text alone, without looking at the disk (so a/.. is removed even when a is a symlink): one / between names, no . names, each name/.. removed, no trailing /. A .. that would go above the start of a relative path stays, one above / is dropped. The empty path is .. A path that is already clean is returned as it is, after one pass over its bytes.

import path

fn main():
    for p in ["a//b/./c/../d/", "", "./", "//", "../../x/..", "/../x"]:
        print(f"[{p}] -> [{path.clean(p)}]")
Output
[a//b/./c/../d/] -> [a/b/d]
[] -> [.]
[./] -> [.]
[//] -> [/]
[../../x/..] -> [../..]
[/../x] -> [/x]

Names and extensions

dir and base follow Go: dir("a") is ., dir("/a") is /, base("a/b/") is b. ext is from the last . of the last name, but a name's first byte doesn't count, so .bashrc has no extension (as in Python, unlike Go):

import path

fn main():
    for p in ["x.tar.gz", ".bashrc", "dir/.env.local", "a/b/"]:
        print(p, path.dir(p), path.base(p), path.ext(p), path.stem(p))
    print(path.with_ext("a/b.md", ".html"), path.with_ext("a.d/b", ".o"), path.with_ext("b.tar.gz", ""))
    print(path.split("a/b.txt"))
Output
x.tar.gz . x.tar.gz .gz x.tar
.bashrc . .bashrc  .bashrc
dir/.env.local dir .env.local .local .env
a/b/ a/b b  b
a/b.html a.d/b.o b.tar
("a/", "b.txt")

with_ext is the replacement for writing p[..len(p) - 3] + ".o" by hand: it leaves a dot in a directory name alone.

Relative paths

rel(base, target) is a path that names target when joined to base, both cleaned first. It is an Err when one is absolute and the other isn't, or when base climbs out with .. further than target (there is no way back down without knowing the directory names):

import path

fn main():
    print(path.rel("a/b", "a/c/d"), path.rel("a", "a"), path.rel("/x", "/x/y/z"))
    print(path.rel("a", "/b"))
Output
Ok("../c/d") Ok(".") Ok("y/z")
Err("path: can't make /b relative to a")

Patterns and glob

matches(pattern, name) matches the whole name:

PatternMatches
*any run of bytes, except /
?one byte, except /
[abc], [a-z]one byte in the set (] first, or - first or last, is itself)
[!a-z], [^a-z]one byte not in the set (and not /)
\xx itself (\* is a star)

A malformed pattern (a [ with no ], a \ at the end) matches nothing. * never makes matching slow: it keeps one place to retry from, so the work is at most the pattern's length times the name's.

glob(pattern) lists the paths that exist and match, sorted. Each /-separated piece of the pattern is matched against one name, and a piece that is just ** matches any number of directories, none included. A name starting with . matches only a piece that starts with ., as in a shell, so ** doesn't wander into .git:

path.glob("src/**/*.tn")          every .tn file below src (src/a.tn, src/x/y/b.tn)
path.glob("*.md")                 the .md files here (relative patterns give relative paths)
path.glob("/etc/*.conf")
path.glob("**/.github/*.yml")     a piece starting with "." may match hidden names

Directories reached through a symlink are followed, like fs.walk.

Speed

bench/std runs the same work in Go (path, path/filepath, and doublestar for **) and Rust (std::path, plus the path-clean, pathdiff and glob crates) on a million paths, a quarter of them needing cleaning. Tern is the fastest of the three at each operation and uses the least memory:

TernGoRust
clean37 ns75 ns200 ns
dir + base + ext + stem45 ns62 ns51 ns
join46 ns140 ns455 ns
rel120 ns170 ns190 ns
matches, 4 patterns18 ns62 ns28 ns (a compiled glob::Pattern)
glob("**/*.tn"), 20,000 files17.5 ms40 ms20 ms
peak memory122 MB216 MB232 MB

clean and the name functions are C in the runtime: an already-clean path (the usual case) is recognised 8 bytes at a time and returned without a copy. glob lists each directory once with fs.list_marked, which knows which entries are directories without a stat. The answers agree with Go's on 200,000 random paths built from a, b, . and /, for clean, dir, base, join and rel.

Source: docs/std/path.md. Every example on this page is compiled and run by tern x test docs.