Skip to content

Add methods to query the directory itself #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::path::{PathBuf};

use libc;
use metadata::{self, Metadata};
use list::{DirIter, open_dir};
use list::{DirIter, open_dir, open_dirfd};

use {Dir, AsPath};

Expand Down Expand Up @@ -50,11 +50,18 @@ impl Dir {

/// List subdirectory of this dir
///
/// You can list directory itself if `"."` is specified as path.
/// You can list directory itself with `list_self`.
pub fn list_dir<P: AsPath>(&self, path: P) -> io::Result<DirIter> {
open_dir(self, to_cstr(path)?.as_ref())
}

/// List this dir
pub fn list_self(&self) -> io::Result<DirIter> {
unsafe {
open_dirfd(libc::dup(self.0))
}
}

/// Open subdirectory
pub fn sub_dir<P: AsPath>(&self, path: P) -> io::Result<Dir> {
self._sub_dir(to_cstr(path)?.as_ref())
Expand Down Expand Up @@ -378,6 +385,18 @@ impl Dir {
}
}

/// Returns the metadata of the directory itself.
pub fn self_metadata(&self) -> io::Result<Metadata> {
unsafe {
let mut stat = mem::zeroed();
let res = libc::fstat(self.0, &mut stat);
if res < 0 {
Err(io::Error::last_os_error())
} else {
Ok(metadata::new(stat))
}
}
}
}

/// Rename (move) a file between directories
Expand Down
16 changes: 10 additions & 6 deletions src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,23 @@ impl DirIter {
}
}

pub fn open_dirfd(fd: libc::c_int) -> io::Result<DirIter> {
let dir = unsafe { libc::fdopendir(fd) };
if dir == std::ptr::null_mut() {
Err(io::Error::last_os_error())
} else {
Ok(DirIter { dir: dir })
}
}

pub fn open_dir(dir: &Dir, path: &CStr) -> io::Result<DirIter> {
let dir_fd = unsafe {
libc::openat(dir.0, path.as_ptr(), libc::O_DIRECTORY|libc::O_CLOEXEC)
};
if dir_fd < 0 {
Err(io::Error::last_os_error())
} else {
let dir = unsafe { libc::fdopendir(dir_fd) };
if dir == ptr::null_mut() {
Err(io::Error::last_os_error())
} else {
Ok(DirIter { dir: dir })
}
open_dirfd(dir_fd)
}
}

Expand Down