Skip to content

Commit

Permalink
Add a access(2) wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
jorickert committed Apr 20, 2019
1 parent af59a15 commit 78d7aea
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
- Added `nix::unistd:seteuid` and `nix::unistd::setegid` for those platforms that do
not support `setresuid` nor `setresgid` respectively.
([#1044](https://github.com/nix-rust/nix/pull/1044))
- Added a `access` wrapper
([#1045](https://github.com/nix-rust/nix/pull/1045))

### Changed
- `PollFd` event flags renamed to `PollFlags` ([#1024](https://github.com/nix-rust/nix/pull/1024/))
Expand Down
25 changes: 25 additions & 0 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2334,3 +2334,28 @@ mod setres {
Errno::result(res).map(drop)
}
}

libc_bitflags!{
/// Options for access()
pub struct AccessFlags : c_int {
/// Test for existence of file.
F_OK;
/// Test for read permission.
R_OK;
/// Test for write permission.
W_OK;
/// Test for execute (search) permission.
X_OK;
}
}

/// Checks the file named by `path` for accessibility according to the flags given by `amode`
/// See [access(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/access.html)
pub fn access<P: ?Sized + NixPath>(path: &P, amode: AccessFlags) -> Result<()> {
let res = path.with_nix_path(|cstr| {
unsafe {
libc::access(cstr.as_ptr(), amode.bits)
}
})?;
Errno::result(res).map(drop)
}
17 changes: 17 additions & 0 deletions test/test_unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use nix::unistd::ForkResult::*;
use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction};
use nix::sys::wait::*;
use nix::sys::stat::{self, Mode, SFlag};
use nix::errno::Errno;
use std::{env, iter};
use std::ffi::CString;
use std::fs::{self, File};
Expand Down Expand Up @@ -574,3 +575,19 @@ fn test_symlinkat() {
target
);
}

#[test]
fn test_access_not_existing() {
let tempdir = tempfile::tempdir().unwrap();
let dir = tempdir.path().join("does_not_exist.txt");
assert_eq!(access(&dir, AccessFlags::F_OK).err().unwrap().as_errno().unwrap(),
Errno::ENOENT);
}

#[test]
fn test_access_file_exists() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("does_exist.txt");
let _file = File::create(path.clone()).unwrap();
assert!(access(&path, AccessFlags::R_OK | AccessFlags::W_OK).is_ok());
}

0 comments on commit 78d7aea

Please sign in to comment.