axfs/api/
mod.rs

1//! [`std::fs`]-like high-level filesystem manipulation operations.
2
3mod dir;
4mod file;
5
6pub use self::dir::{DirBuilder, DirEntry, ReadDir};
7pub use self::file::{File, FileType, Metadata, OpenOptions, Permissions};
8
9use alloc::{string::String, vec::Vec};
10use axio::{self as io, prelude::*};
11
12/// Returns an iterator over the entries within a directory.
13pub fn read_dir(path: &str) -> io::Result<ReadDir> {
14    ReadDir::new(path)
15}
16
17/// Returns the canonical, absolute form of a path with all intermediate
18/// components normalized.
19pub fn canonicalize(path: &str) -> io::Result<String> {
20    crate::root::absolute_path(path)
21}
22
23/// Returns the current working directory as a [`String`].
24pub fn current_dir() -> io::Result<String> {
25    crate::root::current_dir()
26}
27
28/// Changes the current working directory to the specified path.
29pub fn set_current_dir(path: &str) -> io::Result<()> {
30    crate::root::set_current_dir(path)
31}
32
33/// Read the entire contents of a file into a bytes vector.
34pub fn read(path: &str) -> io::Result<Vec<u8>> {
35    let mut file = File::open(path)?;
36    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
37    let mut bytes = Vec::with_capacity(size as usize);
38    file.read_to_end(&mut bytes)?;
39    Ok(bytes)
40}
41
42/// Read the entire contents of a file into a string.
43pub fn read_to_string(path: &str) -> io::Result<String> {
44    let mut file = File::open(path)?;
45    let size = file.metadata().map(|m| m.len()).unwrap_or(0);
46    let mut string = String::with_capacity(size as usize);
47    file.read_to_string(&mut string)?;
48    Ok(string)
49}
50
51/// Write a slice as the entire contents of a file.
52pub fn write<C: AsRef<[u8]>>(path: &str, contents: C) -> io::Result<()> {
53    File::create(path)?.write_all(contents.as_ref())
54}
55
56/// Given a path, query the file system to get information about a file,
57/// directory, etc.
58pub fn metadata(path: &str) -> io::Result<Metadata> {
59    File::open(path)?.metadata()
60}
61
62/// Creates a new, empty directory at the provided path.
63pub fn create_dir(path: &str) -> io::Result<()> {
64    DirBuilder::new().create(path)
65}
66
67/// Recursively create a directory and all of its parent components if they
68/// are missing.
69pub fn create_dir_all(path: &str) -> io::Result<()> {
70    DirBuilder::new().recursive(true).create(path)
71}
72
73/// Removes an empty directory.
74pub fn remove_dir(path: &str) -> io::Result<()> {
75    crate::root::remove_dir(None, path)
76}
77
78/// Removes a file from the filesystem.
79pub fn remove_file(path: &str) -> io::Result<()> {
80    crate::root::remove_file(None, path)
81}
82
83/// Rename a file or directory to a new name.
84/// Delete the original file if `old` already exists.
85///
86/// This only works then the new path is in the same mounted fs.
87pub fn rename(old: &str, new: &str) -> io::Result<()> {
88    crate::root::rename(old, new)
89}