Skip to content
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

Eliminate dependency on the unmaintained "users" crate #51

Merged
merged 2 commits into from
Sep 29, 2024
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
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ serialize = ["serde", "serde_json"]

[dependencies]
libc = "0.2"
nix = "0.26"
nix = { version = "0.28", default-features = false, features = [ "signal", "user" ] }
number_prefix = "0.4"
sysctl = "0.5"
serde = { version="1.0", features = ["derive"], optional=true }
serde_json = { version="1.0", optional=true }
thiserror = "1.0"
users = "0.11.0"
23 changes: 14 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,32 +108,37 @@ pub enum Error {
mod subject {
use super::ParseError;
use std::fmt;
use users::{get_user_by_name, get_user_by_uid};
use nix::unistd::{self, Uid};

/// Represents a user subject
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
pub struct User(pub users::uid_t);
pub struct User(pub Uid);

impl User {
pub fn from_uid(uid: libc::uid_t) -> User {
User(uid as users::uid_t)
User(Uid::from_raw(uid))
}

pub fn from_name(name: &str) -> Result<User, ParseError> {
let uid = get_user_by_name(name)
let uid = unistd::User::from_name(name)
// Note: the only documented error that getpwnam_r may return is
// ERANGE, and Nix is supposed to handle that one, so it should
// "never" return Err
.unwrap_or(None)
.ok_or_else(|| ParseError::UnknownUser(name.into()))?
.uid();
.uid;

Ok(User::from_uid(uid))
Ok(User(uid))
}
}

impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match get_user_by_uid(self.0) {
Some(user) => write!(f, "user:{}", user.name().to_str().ok_or(fmt::Error)?),
None => write!(f, "user:{}", self.0),
match unistd::User::from_uid(self.0) {
Err(e) => write!(f, "user: <{}>", e),
Ok(Some(user)) => write!(f, "user:{}", user.name),
Ok(None) => write!(f, "user:{}", self.0),
}
}
}
Expand Down