directory
import std::fs::directory; · source
Creating, removing, and listing directories. Every operation is a static on Directory, and every failure names the path it happened at.
import std::fmt;
import std::fs::directory::{ Directory };
Directory::create_all("build/cache")?;
for (entry in Directory::entries("src")?) {
if (entry.is_file()) { fmt::println(f"{entry.path().as_str()}"); }
}
Directory::remove_all("build")?;
Types
Directory
type struct Directory {}
| Method | Notes |
|---|---|
create(path) | One directory, mode DEFAULT_DIRECTORY_MODE (0755). Its parent must exist; AlreadyExists if anything is there. |
create_all(path) | mkdir -p. A directory already there is success, including one another process creates at the same moment. |
remove(path) | An empty directory; one with entries fails with DirectoryNotEmpty. |
remove_all(path) | rm -r. A symlink inside is removed itself, not followed. Stops at the first failure. |
copy_all(from, to) | The tree under from copied to to, made with any missing parents. A link to a directory is left out, so the copy cannot reach outside from or loop. |
entries(path) | A listing of the directory, without . and ... |
Files are removed with File::remove, and any entry is moved with Path.rename_to or made absolute with Path.canonicalize.
Static functions
static create(path: Path) -> Result<(), IoError>;
static create(path: Path) -> Result<(), IoError>;Create the directory path. Its parent must exist; see create_all. Fails with AlreadyExists if anything is there.
static create(path: Path) -> Result<(), IoError>;
static create(path: Path) -> Result<(), IoError>;Create the directory path, whose parent must exist; as the copy above.
static create_all(path: Path) -> Result<(), IoError>;
static create_all(path: Path) -> Result<(), IoError>;Create the directory path and every missing directory above it. A directory already there is success, including one another process creates at the same moment; anything else in the way is not.
static remove(path: Path) -> Result<(), IoError>;
static remove(path: Path) -> Result<(), IoError>;Remove the empty directory path. A directory with entries fails with DirectoryNotEmpty; see remove_all.
static remove(path: Path) -> Result<(), IoError>;
static remove(path: Path) -> Result<(), IoError>;Remove the empty directory path; as the copy above.
static copy_all(from: Path, to: Path) -> Result<(), IoError>;
static copy_all(from: Path, to: Path) -> Result<(), IoError>;Copy the directory from and everything in it to to, which is made with any missing parents. A file, or a link to one, is copied as a file; a link to a directory is not followed and is left out, so the copy cannot reach outside from or loop. Stops at the first failure, which names the entry it could not copy.
static remove_all(path: Path) -> Result<(), IoError>;
static remove_all(path: Path) -> Result<(), IoError>;Remove the directory path and everything in it. A symlink inside is removed itself; what it points at is left alone. Stops at the first failure, which names the entry it could not remove.
static entries(path: Path) -> Result<DirectoryEntries, IoError>;
static entries(path: Path) -> Result<DirectoryEntries, IoError>;The entries of the directory path, without . and ...
static entries(path: Path) -> Result<DirectoryEntries, IoError>;
static entries(path: Path) -> Result<DirectoryEntries, IoError>;The entries of the directory path, without . and ..; as the copy above.
DirectoryEntries
type struct DirectoryEntries {}
entries(path) returns a DirectoryEntries, an iterator of DirectoryEntry values that holds the directory open until it is dropped. The order is the filesystem's own. Linux lists with opendir / readdir; Windows with FindFirstFileW / FindNextFileW, so names outside the ANSI code page come back intact (a name that is not valid UTF-16 has no Str form and is skipped).
DirectoryEntry
type struct DirectoryEntry {
private entry_path: PathBuf;
private name_length: i64;
private kind: FileType;
private directory_link: boolean;
}
One entry of a listing: its own name(), its full path() (the listed directory joined with the name), and its file_type(). The type comes from the listing itself, so a symlink is reported as Symlink, not as what it points at; a filesystem that leaves the type unknown in the listing is asked with lstat. metadata() follows a symlink.
Methods
name(&this) -> Str;
name(&this) -> Str;The entry's own name, with no directory part.
path(&this) -> Path;
path(&this) -> Path;The listed directory joined with the entry's name.
file_type(&this) -> FileType;
file_type(&this) -> FileType;The kind of entry, from the listing itself; a symlink is reported as Symlink, not as what it points at.
is_file(&this) -> boolean;
is_file(&this) -> boolean;True when the entry is a regular file, as the listing reports it.
is_directory(&this) -> boolean;
is_directory(&this) -> boolean;True when the entry is a directory, as the listing reports it.
is_symlink(&this) -> boolean;
is_symlink(&this) -> boolean;True when the entry is a symbolic link itself.
metadata(&this) -> Result<Metadata, IoError>;
metadata(&this) -> Result<Metadata, IoError>;What is at the entry's path, following a symlink.
Trait implementations
DirectoryEntries
implement trait Iterator<DirectoryEntry> for struct DirectoryEntries
implement trait Drop for struct DirectoryEntries
DirectoryEntry
implement trait Drop for struct DirectoryEntry
Constants
const DEFAULT_DIRECTORY_MODE: u32 = libc::S_IRWXU | libc::S_IRGRP | libc::S_IXGRP | libc::S_IROTH | libc::S_IXOTH;import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
static Directory::create_all(path: Path) -> Result<(), IoError>Create the directory path and every missing directory above it. A directory already there is success, including one another process creates at the same moment; anything else in the way is not.
value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
for (mut i: i32 = 0; i < n; i++) { ... }
for (item in iterable) { ... }
for ((i, item) in items.iterate().enumerate()) { ... }Two forms. The C-style for (init; condition; step) scopes its loop variable to the body. for (x in expr) iterates an Iterator, a range such as 0..n, or an Iterable, which it consumes: an Array, a Slice of Copy elements, or a fixed-size array. A loop that only borrows writes its borrowing iterator, xs.iter() or xs.iterate_references(). The binding may be a tuple pattern that takes each item apart, nested and with _ elements: enumerate() yields (index, element) with an i64 index, and zip yields (a, b). A loop variable the body never reads is warned about (W0001); write _.
entryfor (item in iterable) { ... }Separates the loop variable from the sequence in a for loop. The sequence is evaluated once; the loop lowers to loop { match (it.next()) { Some(x) => .., None => break } }.
static Directory::entries(path: Path) -> Result<DirectoryEntries, IoError>The entries of the directory path, without . and ...
if (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
static Directory::remove_all(path: Path) -> Result<(), IoError>Remove the directory path and everything in it. A symlink inside is removed itself; what it points at is left alone. Stops at the first failure, which names the entry it could not remove.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Directory {}Directories, by path. Every operation is a static.
type struct DirectoryEntries {}A directory listing in progress: an iterator of DirectoryEntry. Holds the directory open until it is dropped.
type struct DirectoryEntry {}One entry of a directory listing: its name, its full path (the listed directory joined with the name), and what kind of entry it is.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
DirectoryEntry.entry_path: PathBuftype struct PathBuf<A = GlobalAllocator> {}An owned filesystem path that can be extended with push or built by Path.join. It dereferences to Path, so every Path method reads a PathBuf too (file_name, parent, exists, ...); as_path hands the view out.
DirectoryEntry.name_length: i64DirectoryEntry.kind: FileTypetype enum FileType with [Eq, Clone, Debug] {
File;
Directory;
Symlink;
Other;
}The broad category of a filesystem entry.
std::fs::metadataDirectoryEntry.directory_link: booleanconst NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const DEFAULT_DIRECTORY_MODE: u32 = libc::S_IRWXU | libc::S_IRGRP | libc::S_IXGRP | libc::S_IROTH | libc::S_IXOTH;static Directory::create(path: Path) -> Result<(), IoError>Create the directory path. Its parent must exist; see create_all. Fails with AlreadyExists if anything is there.
DirectoryEntry::path(&this) -> PathThe listed directory joined with the entry's name.
std::fs::directoryconst DEFAULT_DIRECTORY_MODE: u32 = libc::S_IRWXU | libc::S_IRGRP | libc::S_IXGRP | libc::S_IROTH | libc::S_IXOTH;IoErrorKind::AlreadyExistsextern "C" function mkdir(path: u8*, mode: u32) -> i32static Directory::remove(path: Path) -> Result<(), IoError>Remove the empty directory path. A directory with entries fails with DirectoryNotEmpty; see remove_all.
static Directory::copy_all(from: Path, to: Path) -> Result<(), IoError>Copy the directory from and everything in it to to, which is made with any missing parents. A file, or a link to one, is copied as a file; a link to a directory is not followed and is left out, so the copy cannot reach outside from or loop. Stops at the first failure, which names the entry it could not copy.
// reservedA reserved keyword with no syntax of its own in the current grammar. The standard library uses it freely as a method and parameter name (Str::from, from: u64).
type struct Path {}A borrowed filesystem path: a view of text owned elsewhere, valid while that text is. A string literal or a Str converts to one where a Path is wanted; PathBuf is the owned form join builds.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) path: Pathtype enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
primitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
type struct IoError {
kind: IoErrorKind;
os_code: i32;
}The error of a failed I/O operation: its kind, the operating system's own code, and, when the operation named one, what it was doing and the path. It prints as could not open config.toml: not found.
(parameter) from: Path(parameter) to: Pathtype struct DirectoryEntries {}A directory listing in progress: an iterator of DirectoryEntry. Holds the directory open until it is dropped.
type struct DirectoryEntry {}One entry of a directory listing: its name, its full path (the listed directory joined with the name), and what kind of entry it is.
std::fs::directorytype struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
DirectoryEntry::file_type(&this) -> FileTypeThe kind of entry, from the listing itself; a symlink is reported as Symlink, not as what it points at.
FileType::SymlinkDirectoryEntry::metadata(&this) -> Result<Metadata, IoError>What is at the entry's path, following a symlink.
std::fs::directory&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
DirectoryEntry::is_file(&this) -> booleanTrue when the entry is a regular file, as the listing reports it.
std::fs::directoryDirectoryEntry::is_directory(&this) -> booleanTrue when the entry is a directory, as the listing reports it.
std::fs::directoryDirectoryEntry::is_symlink(&this) -> booleanTrue when the entry is a symbolic link itself.
std::fs::directorytype struct Metadata {}A snapshot of a path's metadata. POD (no owned resources), freely copied; no drop needed.
implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referencetype trait Iterator {
type Item;
next(mut &this) -> Option<This::Item>;
count(mut &this) -> i64;
fold<Acc, F>(mut &this, initial: Acc, f: F) -> Acc
where F: (Acc, This::Item) -> Acc;
for_each<F>(mut &this, f: F) -> void
where F: (This::Item) -> void;
take(this, n: i64) -> implement Iterator<This::Item>;
skip(this, n: i64) -> implement Iterator<This::Item>;
map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> B;
filter<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
chain<J>(this, other: J) -> implement Iterator<This::Item>
where J: Iterator<This::Item>;
enumerate(this) -> implement Iterator<(i64, This::Item)>;
zip<J>(this, other: J) -> implement Iterator<(This::Item, J::Item)>
where J: Iterator;
collect<C>(this) -> C
where C: FromIterator<This::Item>;
sum<S>(this) -> S
where S: Sum, This: Iterator<S>;
reverse(this) -> implement Iterator<This::Item>
where This: DoubleEndedIterator;
peekable(this) -> implement Peekable<This::Item>;
flat_map<B, F>(this, f: F) -> implement Iterator<B::Item>
where F: (This::Item) -> B, B: Iterator;
flatten(this) -> implement Iterator<This::Item::Item>
where This::Item: Iterator;
take_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
skip_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
step_by(this, step: i64) -> implement Iterator<This::Item>;
filter_map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> Option<B>;
any<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
all<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
find<P>(mut &this, pred: P) -> Option<This::Item>
where P: (&This::Item) -> boolean;
min(mut &this) -> Option<This::Item>
where This::Item: Ord;
max(mut &this) -> Option<This::Item>
where This::Item: Ord;
min_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
max_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
min_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
max_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
last(mut &this) -> Option<This::Item>;
nth(mut &this, n: i64) -> Option<This::Item>;
position<P>(mut &this, pred: P) -> Option<i64>
where P: (This::Item) -> boolean;
product<S>(this) -> S
where S: Product, This: Iterator<S>;
}A source of values handed out one at a time by next, until it returns None. for (x in source) drives one, and the adapter methods below build new iterators from it:
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).