Skip to content

Commit

Permalink
Cleaned up platform-specific code
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewliebenow committed Sep 12, 2024
1 parent b3317e0 commit 7ca27ef
Show file tree
Hide file tree
Showing 22 changed files with 142 additions and 172 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 8 additions & 8 deletions file/find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ fn parse_expression(tokens: &mut Vec<&str>) -> Vec<Expr> {
"-size" => {
tokens.pop();
if let Some(size) = tokens.pop() {
let (size, in_bytes) = if size.ends_with('c') {
(size[..size.len() - 1].parse::<u64>().unwrap_or(0), true)
let (size, in_bytes) = if let Some(st) = size.strip_suffix('c') {
(st.parse::<u64>().unwrap_or(0), true)
} else {
(size.parse::<u64>().unwrap_or(0), false)
};
Expand Down Expand Up @@ -250,15 +250,15 @@ fn evaluate_expression(
match expression {
Expr::Not(inner) => {
let i: Vec<Expr> = vec![f_path.clone(), *inner.clone()];
not_res = evaluate_expression(&i.as_slice(), files.clone(), root_dev)?;
not_res = evaluate_expression(i.as_slice(), files.clone(), root_dev)?;
}
Expr::Or(inner) => {
let i: Vec<Expr> = vec![f_path.clone(), *inner.clone()];
or_res = evaluate_expression(&i.as_slice(), files.clone(), root_dev)?;
or_res = evaluate_expression(i.as_slice(), files.clone(), root_dev)?;
}
Expr::And(inner) => {
let i: Vec<Expr> = vec![f_path.clone(), *inner.clone()];
and_res = evaluate_expression(&i.as_slice(), files.clone(), root_dev)?;
and_res = evaluate_expression(i.as_slice(), files.clone(), root_dev)?;
}
_ => {}
}
Expand Down Expand Up @@ -307,7 +307,7 @@ fn evaluate_expression(
FileType::Fifo => file_type.is_fifo(),
FileType::File => file_type.is_file(),
FileType::Socket => file_type.is_socket(),
FileType::Unknown => return Err(format!("Unknown argument to -type")),
FileType::Unknown => return Err("Unknown argument to -type".to_owned()),
};
if !r {
c_files.remove(file.path());
Expand All @@ -316,15 +316,15 @@ fn evaluate_expression(
Expr::NoUser => {
if let Ok(metadata) = file.metadata() {
let uid = metadata.uid();
if !users::get_user_by_uid(uid).is_none() {
if users::get_user_by_uid(uid).is_some() {
c_files.remove(file.path());
}
}
}
Expr::NoGroup => {
if let Ok(metadata) = file.metadata() {
let gid = metadata.gid();
if !users::get_group_by_gid(gid).is_none() {
if users::get_group_by_gid(gid).is_some() {
c_files.remove(file.path());
}
}
Expand Down
6 changes: 3 additions & 3 deletions ftw/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ enum ProcessFileResult {
}

fn process_file<F, H>(
path_stack: &Vec<Rc<[libc::c_char]>>,
path_stack: &[Rc<[libc::c_char]>],
dir_fd: &FileDescriptor,
entry_filename: Rc<[libc::c_char]>,
follow_symlinks: bool,
Expand All @@ -439,7 +439,7 @@ where
Ok(md) => md,
Err(e) => {
err_reporter(
Entry::new(dir_fd, &path_stack, &entry_filename, None),
Entry::new(dir_fd, path_stack, &entry_filename, None),
Error::new(e, ErrorKind::Stat),
);
return ProcessFileResult::NotProcessed;
Expand Down Expand Up @@ -583,7 +583,7 @@ where
Err(e) => {
if let Some(path_stack) = &path_stack {
err_reporter(
Entry::new(&starting_dir, &path_stack, &filename, None),
Entry::new(&starting_dir, path_stack, &filename, None),
Error::new(e, ErrorKind::Open),
);
}
Expand Down
2 changes: 1 addition & 1 deletion gettext-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub fn textdomain<T: Into<Vec<u8>>>(domainname: T) -> Result<Vec<u8>, std::io::E
}

pub fn gettext<T: Into<String>>(msgid: T) -> String {
return msgid.into();
msgid.into()
}

#[macro_export]
Expand Down
2 changes: 1 addition & 1 deletion m4/test-manager/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ fn update_snapshots(args: &Args, update: &UpdateSnapshots) {
return false;
}

if let Some(name) = update.test_case_name.as_ref().map(|s| s.as_str()) {
if let Some(name) = update.test_case_name.as_deref() {
if name != entry.path().file_stem().unwrap().to_str().unwrap() {
return false;
}
Expand Down
1 change: 1 addition & 0 deletions plib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license = "MIT"
repository = "https://github.com/rustcoreutils/posixutils-rs.git"

[dependencies]
cfg-if = "1.0"
libc.workspace = true

[lib]
Expand Down
17 changes: 8 additions & 9 deletions plib/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,21 @@ use std::path::PathBuf;

pub fn input_stream(pathname: &PathBuf, dashed_stdin: bool) -> io::Result<Box<dyn Read>> {
// open file, or stdin
let file: Box<dyn Read>;
let path_str = pathname.as_os_str();
if dashed_stdin && path_str == "-" {
file = Box::new(io::stdin().lock());
} else if !dashed_stdin && path_str == "" {
file = Box::new(io::stdin().lock());
} else {
file = Box::new(fs::File::open(pathname)?);
}

let file: Box<dyn Read> =
if (dashed_stdin && path_str == "-") || (!dashed_stdin && path_str.is_empty()) {
Box::new(io::stdin().lock())
} else {
Box::new(fs::File::open(pathname)?)
};

Ok(file)
}

pub fn input_stream_opt(pathname: &Option<PathBuf>) -> io::Result<Box<dyn Read>> {
match pathname {
Some(path) => input_stream(&path, false),
Some(path) => input_stream(path, false),
None => input_stream(&PathBuf::new(), false),
}
}
Expand Down
3 changes: 1 addition & 2 deletions plib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@
pub mod curuser;
pub mod group;
pub mod io;
// TODO: Remove "libc_aliases" when https://github.com/rust-lang/libc/issues/3190 is resolved
pub mod libc_aliases;
pub mod lzw;
pub mod modestr;
pub mod platform;
pub mod sccsfile;
pub mod testing;
pub mod utmpx;
Expand Down
10 changes: 0 additions & 10 deletions plib/src/libc_aliases.rs

This file was deleted.

22 changes: 0 additions & 22 deletions plib/src/libc_aliases/musl.rs

This file was deleted.

58 changes: 58 additions & 0 deletions plib/src/platform.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// TODO
// Avoid restating local alias names
cfg_if::cfg_if! {
if #[cfg(target_env = "musl")] {
// https://git.musl-libc.org/cgit/musl/tree/include/utmpx.h?id=1e7f0fcd7ff2096904fd93a2ee6d12a2392be392
pub const EMPTY: libc::c_short = 0_i16;
pub const RUN_LVL: libc::c_short = 1_i16;
pub const BOOT_TIME: libc::c_short = 2_i16;
pub const NEW_TIME: libc::c_short = 3_i16;
pub const OLD_TIME: libc::c_short = 4_i16;
pub const INIT_PROCESS: libc::c_short = 5_i16;
pub const LOGIN_PROCESS: libc::c_short = 6_i16;
pub const USER_PROCESS: libc::c_short = 7_i16;
pub const DEAD_PROCESS: libc::c_short = 8_i16;

// Remove when https://github.com/rust-lang/libc/issues/3190 is resolved
// https://github.com/rust-lang/libc/commit/e3caaf6b0ea08ae294e25a861022c256a7535ec4#diff-5822a2981791fb0bb7689a921abdc2133cc73116ee125eabefad3a9374056b7a
extern "C" {
pub fn getutxent() -> *mut libc::utmpx;
pub fn getutxid(ut: *const libc::utmpx) -> *mut libc::utmpx;
pub fn getutxline(ut: *const libc::utmpx) -> *mut libc::utmpx;
pub fn pututxline(ut: *const libc::utmpx) -> *mut libc::utmpx;
pub fn setutxent();
pub fn endutxent();
}

type LocalPIoctlOp = libc::c_int;
type LocalPPriorityWhichT = libc::c_int;
} else {
pub use libc::{
endutxent,
getutxent,
setutxent,
BOOT_TIME,
DEAD_PROCESS,
EMPTY,
INIT_PROCESS,
LOGIN_PROCESS,
NEW_TIME,
OLD_TIME,
RUN_LVL,
USER_PROCESS,
};

type LocalPIoctlOp = libc::c_ulong;

cfg_if::cfg_if! {
if #[cfg(target_os = "macos")] {
type LocalPPriorityWhichT = libc::c_int;
} else {
type LocalPPriorityWhichT = libc::__priority_which_t;
}
}
}
}

pub type PIoctlOp = LocalPIoctlOp;
pub type PPriorityWhichT = LocalPPriorityWhichT;
4 changes: 2 additions & 2 deletions plib/src/sccsfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ fn parse_deltas(lines: &[&str]) -> Result<Vec<SccsDelta>, &'static str> {
comments: String::new(),
});
} else if in_delta_section {
if line.starts_with("c ") {
current_comments.push_str(&line[2..]);
if let Some(st) = line.strip_prefix("c ") {
current_comments.push_str(st);
current_comments.push('\n');
} else if line.starts_with("e") {
if let Some(last_delta) = deltas.last_mut() {
Expand Down
23 changes: 10 additions & 13 deletions plib/src/utmpx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
//

extern crate libc;
// TODO: Remove "libc_aliases" when https://github.com/rust-lang/libc/issues/3190 is resolved
use crate::libc_aliases::{endutxent, getutxent, setutxent};
use crate::platform::{self, endutxent, getutxent, setutxent};
use std::ffi::CStr;

#[derive(Debug)]
Expand All @@ -24,18 +23,16 @@ pub struct Utmpx {
}

pub fn ut_type_str(typ: libc::c_short) -> &'static str {
// TODO: Remove "libc_aliases" when https://github.com/rust-lang/libc/issues/3190 is resolved
use crate::libc_aliases as libc;
match typ {
libc::BOOT_TIME => "BOOT_TIME",
libc::DEAD_PROCESS => "DEAD_PROCESS",
libc::EMPTY => "EMPTY",
libc::INIT_PROCESS => "INIT_PROCESS",
libc::LOGIN_PROCESS => "LOGIN_PROCESS",
libc::NEW_TIME => "NEW_TIME",
libc::OLD_TIME => "OLD_TIME",
libc::RUN_LVL => "RUN_LVL",
libc::USER_PROCESS => "USER_PROCESS",
platform::BOOT_TIME => "BOOT_TIME",
platform::DEAD_PROCESS => "DEAD_PROCESS",
platform::EMPTY => "EMPTY",
platform::INIT_PROCESS => "INIT_PROCESS",
platform::LOGIN_PROCESS => "LOGIN_PROCESS",
platform::NEW_TIME => "NEW_TIME",
platform::OLD_TIME => "OLD_TIME",
platform::RUN_LVL => "RUN_LVL",
platform::USER_PROCESS => "USER_PROCESS",

_ => "(unknown)",
}
Expand Down
40 changes: 3 additions & 37 deletions process/renice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use clap::Parser;
use errno::{errno, set_errno};
use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory};
use libc::{getpwnam, passwd};
use plib::platform::PPriorityWhichT;
use plib::PROJECT_NAME;
use std::ffi::CString;
use std::io;
Expand Down Expand Up @@ -82,24 +83,7 @@ fn parse_id(which: u32, input: &str) -> Result<u32, &'static str> {
fn xgetpriority(which: u32, id: u32) -> io::Result<i32> {
set_errno(errno::Errno(0));

// Prevent accidental shadowing by using a block
let which_cast = {
#[cfg(all(not(target_os = "macos"), not(target_env = "musl")))]
{
which
}

#[cfg(all(not(target_os = "macos"), target_env = "musl"))]
{
which as i32
}

#[cfg(target_os = "macos")]
{
which as i32
}
};
let res = unsafe { libc::getpriority(which_cast, id) };
let res = unsafe { libc::getpriority(which as PPriorityWhichT, id) };

let errno_res = errno().0;
if errno_res == 0 {
Expand All @@ -112,25 +96,7 @@ fn xgetpriority(which: u32, id: u32) -> io::Result<i32> {
}

fn xsetpriority(which: u32, id: u32, prio: i32) -> io::Result<()> {
// Prevent accidental shadowing by using a block
let which_cast = {
#[cfg(all(not(target_os = "macos"), not(target_env = "musl")))]
{
which
}

#[cfg(all(not(target_os = "macos"), target_env = "musl"))]
{
which as i32
}

#[cfg(target_os = "macos")]
{
which as i32
}
};

let res = unsafe { libc::setpriority(which_cast, id, prio) };
let res = unsafe { libc::setpriority(which as PPriorityWhichT, id, prio) };

if res < 0 {
let e = io::Error::last_os_error();
Expand Down
2 changes: 2 additions & 0 deletions sys/ipcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,8 @@ fn get_current_date() -> String {
}

fn display_ipc_status(args: &Args) {
// TODO:
// - add source
println!("IPC status from {} as of {}", "source", get_current_date());

if args.message_queues {
Expand Down
Loading

0 comments on commit 7ca27ef

Please sign in to comment.