Files
std/io/path.sakura
T
2026-10-28 00:51:45 -05:00

709 lines
22 KiB
Plaintext

#! @file path.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains paths, which `std::io` takes and gives for every file it names, and
#! the ways of making one from another: taking its parent, joining, resolving, and
#! making one relative to another. Nothing here reads the file system, so `..` is
#! worked out from the text alone; `std::io` is what asks the system.
#! `std::net`'s `uri::from_path` and `uri::to_path` turn a path into a `file`
#! URI and back.
import system;
module std::io;
# I hate Windows :)
when os == windows {
pub const path_delim: u8 = '\\';
pub const path_invalid_chars: strview = "<>:\"/\\|?*";
} else when os == linux {
pub const path_delim: u8 = '/';
pub const path_invalid_chars: strview = "\\";
} else when os == macos {
pub const path_delim: u8 = '/';
pub const path_invalid_chars: strview = ":\\";
}
#! A path (or filepath, pathname, or similar) is a string that uniquely
#! identifies an item in a hierarchical file system. Generally, a path is
#! composed of directory names, special format specifiers, and optionally a
#! filename, all separated by delimiters.
#!
#! A path can be either relative or absolute. A relative path is one in relation
#! to another, most often the working directory. An absolute path indicates a
#! location regardless of the current directory; that is, it specifies all path
#! components starting from the file system's root, and does not depend on
#! context like a relative path does.
#!
#! A parsed path holds its text in a normal form: its root, then its segments
#! joined by one `path_delim` each. Repeated delimiters and `.` segments are
#! dropped, as is a delimiter at the end, and a relative path left with nothing
#! is `.`. A `..` segment is kept, since what it leads back to depends on links
#! the file system holds; `resolve` is what works `..` out, from the text alone.
#! So two paths are equal when their normal forms are.
#!
#! Paths made from other paths take memory from the same allocator as the path
#! they are made from.
#!
#! @sa https://en.wikipedia.org/wiki/Path_(computing)
pub struct path
: owning
, hashable
, equatable
, copyable
, moveable
{
var _text: string;
var _root: u64;
}
#! The number of bytes the path holds.
#! @param this The path to measure.
#! @returns How many bytes of text it holds, which is no more than its capacity.
pub val path::length: u64 {
get => this._text.length;
}
#! Whether the path is empty.
#! @param this The path to measure.
#! @returns If the path is empty or populated.
pub val path::empty: bool {
get => this.length == 0;
}
#! Provides read only access to the root of a path, which is where it starts
#! from before its first segment.
#! @param this The path to get the root of.
#! @returns A view of the root, such as `/`, `C:\`, `C:`, `\`, or
#! `\\server\share\`, which is empty for a relative path.
pub val path::root: strview {
get => this.view().substr(0, this._root);
}
#! Indicates if a path is absolute, naming the same place whatever the working
#! directory is.
#! @param this The path to check.
#! @returns Whether the path is absolute.
#! @remarks On Windows, `C:foo` is relative to the working directory of drive
#! `C:`, and `\foo` to the root of the working directory's drive, so
#! neither is absolute; only a root ending in a delimiter after a
#! drive or share is.
pub val path::is_absolute: bool {
get {
if !this.is_rooted() {
return false;
}
when os == windows {
return this._root > 1;
}
return true;
}
}
#! Indicates if a path is a directory.
#! @param this The path to check.
#! @returns Whether the path is a directory.
pub val path::is_directory: bool {
get {
return match info(this) {
value(&i) => i.kind == file_kind::directory,
error(_) => false
};
}
}
#! Provides read only access to the name a path ends with.
#! @param this The path to get the name of.
#! @returns A view of the last segment, which is empty where the path is only a
#! root, or is `.` or ends in `..`.
pub val path::name: strview {
get {
val text := this.view();
val start := this.last_start();
val name := text.substr(start, text.length - start);
return name == ".."
? strview::empty()
: name;
}
}
#! Provides read only access to the name a path ends with, without its
#! extension.
#! @param this The path to get the stem of.
#! @returns A view of the name before its last `.`, or the whole name where it
#! has no extension.
pub val path::stem: strview {
get {
val name := this.name;
val dot := path::dot_of(name);
return dot != 0
? name.substr(0, dot)
: name;
}
}
#! Provides read only access to the extension of the name a path ends with.
#! @param this The path to get the extension of.
#! @returns A view of the name after its last `.`, without the `.`, which is
#! empty where it has none. A name starting with its only `.`, such as
#! `.profile`, has no extension.
pub val path::extension: strview {
get {
val name := this.name;
val dot := path::dot_of(name);
return dot != 0
? name.substr(dot + 1, name.length - dot - 1)
: strview::empty();
}
}
#! Creates an empty path.
#! @returns The created path.
pub def path::new(): path {
return path {};
}
#! Parses text as a path, in the form of the platform checked for.
#! @param text The text to parse, such as `/usr/lib`, `../notes.txt`, or on
#! Windows `C:\Users` or `\\server\share\file`.
#! @param alloc The optional allocator for the text the path holds.
#! @returns The path, in its normal form, or why the text is not one.
#! @remarks On Windows, `/` also separates segments, and is written as `\`, and
#! a drive's letter is written in upper case.
pub def path::parse(
text: strview,
alloc: maybe<&mut allocator> = nothing{}
): result<path, failure> {
if text.is_empty() {
return failure { message = $"a path cannot be empty" };
}
var made := path { _text = string::new(alloc), _root = 0 };
made._text.reserve(text.length);
val start := path::read_root(text, &mut made._text);
if start is none {
return failure { message = $"`{text}` does not name both a server and a share" };
}
made._root = made._text.length;
var at := start.some;
while at < text.length {
if path::is_delim(text[at]) {
at++;
continue;
}
var end := at;
while end < text.length && !path::is_delim(text[end]) {
end++;
}
val part := text.substr(at, end - at);
at = end;
if part == "." {
continue;
}
val bad := path::invalid_in(part);
if bad is some {
return failure {
message = $"`{text}` holds `{part.substr(bad.some, 1)}`, which a path cannot"
};
}
if made._text.length > made._root {
made._text.push(path_delim);
}
made._text.append(part);
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Creates a copy of the provided path.
#! @param other The path to copy.
#! @returns The copy, which owns its own text, with the other's allocator.
pub def path::copy_of(other: &path): path {
return path {
_text = string::copy_of(&other._text),
_root = other._root
};
}
#! Creates a new path by moving the text of another path into it.
#! @param other The path to move from, which holds no text after.
#! @returns The moved path, which takes the text and allocator with it.
pub def path::move_of(other: &mut path): path {
val made: path = path {
_text = string::move_of(&mut other._text),
_root = other._root
};
other._root = 0;
return made;
}
#! Views the text of a path, in its normal form.
#! @param this The path to view.
#! @returns A view of its text, which is only good until the path closes.
pub def path::view(&this): strview {
return this._text.view();
}
#! Views each segment of a path after its root, in turn.
#! @param this The path to split.
#! @returns The segments, in order, each viewing into the path's text, so they
#! are only good for as long as it is. A path that is only a root, or
#! is `.`, has none.
pub def path::segments(&this): splits {
if this.is_dot() || this._text.length == this._root {
return splits::empty();
}
val rest := this.view().substr(this._root, this._text.length - this._root);
return rest.split(path_delim);
}
# TODO: Move this to being a property.
#! Makes the path of the directory holding what a path names, from its text.
#! @param this The path to take the parent of.
#! @returns The path without its last segment, which is `.` where only one
#! segment of a relative path was left. A path ending in `..` has
#! another `..` added instead, since dropping it would lead down rather
#! than up. A path that is only a root, or is `.`, has no parent.
pub def path::parent(&this): maybe<path> {
val text := this.view();
if this.is_dot() || text.length == this._root {
return nothing{};
}
var made := this.blank();
val start := this.last_start();
made._root = this._root;
if text.substr(start, text.length - start) == ".." {
made._text.append(text);
made._text.push(path_delim);
made._text.append("..");
return move(made);
}
# The delimiter before the last segment goes with it, unless it ends the root.
val end := start > this._root ? start - 1 : start;
made._text.append(text.substr(0, end));
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Joins another path onto the end of this one.
#! @param this The path to start from.
#! @param other The path to follow from there.
#! @returns The joined path. Where the other is absolute it is the other alone,
#! since it names the same place from anywhere, and where either is `.`
#! it is the other one.
#! @remarks On Windows, a path starting at a root without a drive, as `\foo`, is
#! joined onto this one's drive or share. A path on a drive without a
#! root, as `C:foo`, is joined onto this one where it is on the same
#! drive, and is taken alone where it is not.
pub def path::join(&this, other: &path): path {
return this.joined(other, this._text.alloc);
}
#! Joins a path, given as text, onto the end of this one, as `join` of the path
#! the text is does.
#!
#! The text is taken to be one the program wrote, as `dir.join("lib")`, so text
#! that is not a path is a mistake in the program, and stops it. Text from
#! outside the program is parsed by `path::parse`, which says why it is not a
#! path, and the path it gives is joined instead.
#! @param this The path to start from.
#! @param text The text of the path to follow from there, such as `lib` or
#! `../include`.
#! @returns The joined path.
pub def path::join(&this, text: strview): path {
var parsed := path::parse(text, this._text.alloc);
if parsed is value(&other) {
return this.joined(other, this._text.alloc);
}
system::fd::stderr.put($"sakura: `{text}` is not a path, so it cannot be joined onto one\n");
system::abort();
return this.blank();
}
#! Resolves a path against a base, from the text alone: joins it onto the base,
#! then has each `..` take away the segment before it.
#! @param this The path to resolve, which is taken as it is where absolute.
#! @param base The path that a relative one is taken from, as the working
#! directory is by `std::io::absolute`.
#! @returns The resolved path, which holds no `..` after another segment, and
#! none at all where it has a root, since nothing is above a root.
#! @remarks Where the file system holds links, `..` after one leads back from
#! what the link leads to, which this does not ask the system about.
pub def path::resolve(&this, base: &path): path {
val joined := base.joined(this, this._text.alloc);
var parts := vector::<strview>::new();
for part in joined.segments() {
if part != ".." {
parts.append(part);
continue;
}
if parts.length > 0 && parts.at(parts.length - 1) != ".." {
parts.remove_at(parts.length - 1);
continue;
}
if !joined.is_rooted() {
parts.append(part);
}
}
var made := this.blank();
made._text.append(joined.root);
made._root = joined._root;
for i in 0..parts.length {
if i > 0 {
made._text.push(path_delim);
}
made._text.append(parts.at(i));
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Makes the path that leads from a base to this one, from the text alone.
#! @param this The path to lead to.
#! @param base The path to lead from.
#! @returns A relative path, which `base.join` turns back into this one, as
#! `../lib/std` from `/usr/share` to `/usr/lib/std`, and `.` where the
#! two are the same. There is none where their roots differ, as one
#! being absolute and the other relative, or where the base has a `..`
#! past what they share, since what that leads back from is unknown.
pub def path::relative_to(&this, base: &path): maybe<path> {
if this.root != base.root {
return nothing{};
}
val mine := this.segments().to_vector();
val theirs := base.segments().to_vector();
var shared := 0u;
while shared < mine.length && shared < theirs.length {
val a: strview = mine.at(shared);
val b: strview = theirs.at(shared);
if a != b {
break;
}
shared++;
}
for i in shared..theirs.length {
if theirs.at(i) == ".." {
return nothing{};
}
}
var made := this.blank();
for _ in shared..theirs.length {
made.push_segment("..");
}
for i in shared..mine.length {
made.push_segment(mine.at(i));
}
if made._text.length == 0 {
made._text.push('.');
}
return move(made);
}
#! Tells whether a path is a base or lies within it, by whole segments, so
#! `/usr/lib` starts with `/usr` but not with `/us`.
#! @param this The path to check.
#! @param base The path it may start with.
#! @returns Whether the base's root and segments begin this path. Every relative
#! path starts with `.`.
pub def path::starts_with(&this, base: &path): bool {
if this._root != base._root || this.root != base.root {
return false;
}
if base.is_dot() || base._text.length == base._root {
return true;
}
val mine := this.view();
val theirs := base.view();
if !mine.starts_with(theirs) {
return false;
}
return mine.length == theirs.length || mine[theirs.length] == path_delim;
}
#! Makes a path naming something else in the same directory.
#! @param this The path whose name to replace.
#! @param name The name to give it instead, which is one segment.
#! @returns The path with the name replaced, or why it cannot be: the path has
#! no name to replace, or the name is empty, `.`, `..`, or holds a
#! delimiter or something else a path cannot.
pub def path::with_name(&this, name: strview): result<path, failure> {
if this.name.is_empty() {
return failure { message = $"`{this.view()}` has no name to replace" };
}
if name.is_empty() || name == "." || name == ".." {
return failure { message = $"`{name}` is not a name" };
}
val bad := path::invalid_in(name);
if bad is some {
return failure { message = $"`{name}` holds `{name.substr(bad.some, 1)}`, which a name cannot" };
}
var made := this.blank();
made._text.append(this.view().substr(0, this.last_start()));
made._text.append(name);
made._root = this._root;
return move(made);
}
#! Makes a path whose name has another extension, as `main.o` from
#! `main.sakura`.
#! @param this The path whose extension to replace.
#! @param extension The extension, without its `.`, or empty to take the
#! extension away.
#! @returns The path with the extension replaced, or added where the name had
#! none, or why it cannot be: the path has no name, or the extension
#! holds a delimiter or something else a path cannot.
pub def path::with_extension(&this, extension: strview): result<path, failure> {
if this.name.is_empty() {
return failure { message = $"`{this.view()}` has no name to give an extension" };
}
val bad := path::invalid_in(extension);
if bad is some {
return failure {
message = $"`{extension}` holds `{extension.substr(bad.some, 1)}`, which a name cannot"
};
}
var made := this.blank();
made._text.append(this.view().substr(0, this.last_start()));
made._text.append(this.stem);
if !extension.is_empty() {
made._text.push('.');
made._text.append(extension);
}
made._root = this._root;
return move(made);
}
#! Gives back the memory holding the text of a path.
#! @param this The path to close.
pub def path::close(&mut this): void {
this._text.close();
this._root = 0;
}
#! Compares one path to another by equality.
#! @param this The path to compare against.
#! @param other The path to compare with.
#! @returns Whether both have the same normal form.
pub def path::equals(&this, other: &path): bool {
return this._text.equals(&other._text);
}
#! Hashes the provided path.
#! @param this The path to hash.
#! @returns The hash code of its normal form, which equal paths share.
pub def path::hash(&this): u64 {
return this._text.hash();
}
# Joins another path onto the end of this one, as `join` does, into memory from
# the allocator given.
def path::joined(&this, other: &path, alloc: maybe<&mut allocator>): path {
var made := path { _text = string::new(alloc), _root = 0 };
when os == windows {
if other._root > 0 && !other.is_absolute {
return this.joined_on_drive(other, alloc);
}
}
if other.is_absolute || this.is_dot() {
made._text.append(other.view());
made._root = other._root;
return move(made);
}
made._text.append(this.view());
made._root = this._root;
if !other.is_dot() {
if this._text.length > this._root {
made._text.push(path_delim);
}
made._text.append(other.view());
}
return move(made);
}
# Joins a Windows path that starts at a root without a drive, as `\foo`, or on a
# drive without a root, as `C:foo`, onto the end of this one.
def path::joined_on_drive(&this, other: &path, alloc: maybe<&mut allocator>): path {
var made := path { _text = string::new(alloc), _root = 0 };
val root := this.root;
# `\foo` keeps this path's drive or share: its root, less the delimiter ending it.
if other._root == 1 {
val drive := root.length > 1 && path::is_delim(root[root.length - 1])
? root.substr(0, root.length - 1)
: root;
val keeps := drive.length > 1 ? drive : strview::empty();
made._text.append(keeps);
made._text.append(other.view());
made._root = keeps.length + 1;
return move(made);
}
# `C:foo` follows on from this path where it is on drive `C:`, and stands alone
# where it is not.
if root.length >= 2 && root[0] == other.view()[0] && root[1] == ':' {
made._text.append(this.view());
made._root = this._root;
if other._text.length > other._root {
if this._text.length > this._root {
made._text.push(path_delim);
}
made._text.append(other.view().substr(other._root, other._text.length - other._root));
}
return move(made);
}
made._text.append(other.view());
made._root = other._root;
return move(made);
}
# A path with no text yet, whose memory comes from the same allocator as this one.
def path::blank(&this): path {
return path { _text = string::new(this._text.alloc), _root = 0 };
}
# Adds a segment to the end of a path being made, after a delimiter where the path
# already holds something past its root.
def path::push_segment(&mut this, part: strview): void {
if this._text.length > this._root {
this._text.push(path_delim);
}
this._text.append(part);
}
# Whether the path is `.`, the relative path with nothing in it.
def path::is_dot(&this): bool {
return this._root == 0 && this.view() == ".";
}
# Whether the path's root ends in a delimiter, so nothing is above it.
def path::is_rooted(&this): bool {
return this._root > 0 && this.view()[this._root - 1] == path_delim;
}
# Where the last segment begins, or the end of the text where there is none.
def path::last_start(&this): u64 {
val text := this.view();
if this.is_dot() {
return text.length;
}
var at := text.length;
while at > this._root && text[at - 1] != path_delim {
at--;
}
return at;
}
def path::is_delim(byte: u8): bool {
when os == windows {
return byte == '/' || byte == '\\';
}
return byte == path_delim;
}
# Writes the root the text starts with into the path's text, in normal form, and
# gives the index after it, or `nothing` where it starts as a share without
# naming one.
def path::read_root(text: strview, into: &mut string): maybe<u64> {
var at := 0u;
when os == windows {
if text.length >= 2 && path::is_delim(text[0]) && path::is_delim(text[1]) {
return path::read_share(text, into);
}
if text.length >= 2 && text[0].is_alpha && text[1] == ':' {
into.push(text[0].to_upper);
into.push(':');
at = 2;
if at == text.length || !path::is_delim(text[at]) {
return at;
}
}
}
if at < text.length && path::is_delim(text[at]) {
into.push(path_delim);
}
while at < text.length && path::is_delim(text[at]) {
at++;
}
return at;
}
# Writes a Windows share, as `\\server\share\`, into the path's text, and gives
# the index after it, or `nothing` where either name is missing.
def path::read_share(text: strview, into: &mut string): maybe<u64> {
var at := 2u;
into.push(path_delim);
into.push(path_delim);
for _ in 0..2 {
val start := at;
while at < text.length && !path::is_delim(text[at]) {
at++;
}
if at == start {
return nothing{};
}
into.append(text.substr(start, at - start));
into.push(path_delim);
while at < text.length && path::is_delim(text[at]) {
at++;
}
}
return at;
}
# Gives the index of the first byte of a segment that no path can hold, which is
# a zero byte, a delimiter, or one of `path_invalid_chars`.
def path::invalid_in(part: strview): maybe<u64> {
for index in 0..part.length {
val byte := part[index];
if byte == 0 || path::is_delim(byte) || path_invalid_chars.contains(&byte) {
return index;
}
}
return nothing{};
}
# Gives the index of the `.` before the extension of a name, or `0` where it has
# none, since a name starting with its only `.` is hidden rather than extended.
def path::dot_of(name: strview): u64 {
var at := name.length;
while at > 1 {
at--;
if name[at] == '.' {
return at;
}
}
return 0;
}