Skip to content
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
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,6 @@ ignored_unit_patterns = "allow" # 21
similar_names = "allow" # 20
needless_pass_by_value = "allow" # 16
float_cmp = "allow" # 12
items_after_statements = "allow" # 11
return_self_not_must_use = "allow" # 8
inline_always = "allow" # 6
fn_params_excessive_bools = "allow" # 6
Expand Down
13 changes: 7 additions & 6 deletions src/bin/uudoc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ use std::{
use clap::{Arg, Command};
use clap_complete::Shell;
use clap_mangen::Man;
use fluent_syntax::ast::{Entry, Message, Pattern};
use fluent_syntax::parser;
use fluent_syntax::{
ast::{
Entry, Expression, InlineExpression, Message, Pattern,
PatternElement::{Placeable, TextElement},
},
parser,
};
use jiff::Zoned;
use regex::Regex;
use textwrap::{fill, indent, termwidth};
Expand Down Expand Up @@ -447,10 +452,6 @@ impl MDWriter<'_, '_> {
if id.name == key {
// Simple text extraction - just concatenate text elements
let mut result = String::new();
use fluent_syntax::ast::{
Expression, InlineExpression,
PatternElement::{Placeable, TextElement},
};
for element in elements {
if let TextElement { ref value } = element {
result.push_str(value);
Expand Down
4 changes: 2 additions & 2 deletions src/uu/chcon/src/chcon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,8 @@ fn change_file_context(
context: &SELinuxSecurityContext,
path: &Path,
) -> Result<()> {
type SetValueProc = fn(&OpaqueSecurityContext, &CStr) -> selinux::errors::Result<()>;

match &options.mode {
CommandLineMode::Custom {
user,
Expand Down Expand Up @@ -673,8 +675,6 @@ fn change_file_context(
Error::from_io1(translate!("chcon-op-creating-security-context"), path, err)
})?;

type SetValueProc = fn(&OpaqueSecurityContext, &CStr) -> selinux::errors::Result<()>;

let list: &[(&Option<OsString>, SetValueProc)] = &[
(user, OpaqueSecurityContext::set_user),
(role, OpaqueSecurityContext::set_role),
Expand Down
4 changes: 2 additions & 2 deletions src/uu/cksum/src/cksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ use uucore::translate;
/// 2>/dev/full does not abort
/// This matches GNU cksum's --debug behavior
fn print_cpu_debug_info() {
let features = SimdPolicy::detect();

fn print_feature(name: &str, available: bool) {
if available {
let _ = writeln!(stderr(), "using {name} hardware support");
Expand All @@ -32,6 +30,8 @@ fn print_cpu_debug_info() {
}
}

let features = SimdPolicy::detect();

// x86/x86_64
print_feature("avx512", features.has_avx512());
print_feature("avx2", features.has_avx2());
Expand Down
3 changes: 1 addition & 2 deletions src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2384,8 +2384,7 @@ fn calculate_dest_permissions(
let mode = handle_no_preserve_mode(options, permissions.mode());

// Apply umask
use uucore::mode::get_umask;
let mode = mode & !get_umask();
let mode = mode & !uucore::mode::get_umask();
permissions.set_mode(mode);
permissions
}
Expand Down
3 changes: 2 additions & 1 deletion src/uu/df/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,6 @@ mod tests {

#[test]
fn test_row_formatter_with_round_up_byte_values() {
init();
fn get_formatted_values(bytes: u64, bytes_used: u64, bytes_avail: u64) -> Vec<Cell> {
let options = Options {
block_size: BlockSize::Bytes(1000),
Expand All @@ -967,6 +966,8 @@ mod tests {
RowFormatter::new(&row, &options, false).get_cells()
}

init();

assert!(compare_cell_content(
get_formatted_values(100, 100, 0),
vec!("1", "1", "0")
Expand Down
12 changes: 7 additions & 5 deletions src/uu/du/src/du.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,10 @@ fn safe_du(
};

'file_loop: for entry_name in entries {
const S_IFMT: u32 = 0o170_000;
const S_IFDIR: u32 = 0o040_000;
const S_IFLNK: u32 = 0o120_000;

// First get the lstat (without following symlinks) to check if it's a symlink
let lstat = match dir_fd.stat_at(&entry_name, SymlinkBehavior::NoFollow) {
Ok(stat) => stat,
Expand All @@ -439,9 +443,6 @@ fn safe_du(
};

// Check if it's a symlink
const S_IFMT: u32 = 0o170_000;
const S_IFDIR: u32 = 0o040_000;
const S_IFLNK: u32 = 0o120_000;
#[allow(clippy::unnecessary_cast)]
let is_symlink = (lstat.st_mode as u32 & S_IFMT) == S_IFLNK;

Expand Down Expand Up @@ -575,11 +576,12 @@ fn du_regular(
ancestors: Option<&mut HashSet<FileInfo>>,
symlink_depth: Option<usize>,
) -> Result<Stat, Box<mpsc::SendError<UResult<StatPrintInfo>>>> {
// Maximum symlink depth to prevent infinite loops
const MAX_SYMLINK_DEPTH: usize = 40;

let mut default_ancestors = HashSet::default();
let ancestors = ancestors.unwrap_or(&mut default_ancestors);
let symlink_depth = symlink_depth.unwrap_or(0);
// Maximum symlink depth to prevent infinite loops
const MAX_SYMLINK_DEPTH: usize = 40;

// Add current directory to ancestors if it's a directory
let my_inode = if my_stat.metadata.is_dir() {
Expand Down
13 changes: 7 additions & 6 deletions src/uu/expr/src/syntax_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,9 @@ fn check_posix_regex_errors(pattern: &str) -> ExprResult<()> {
/// Build a regex from a pattern string with locale-aware encoding
fn build_regex(pattern_bytes: Vec<u8>) -> ExprResult<(Regex, String)> {
use onig::EncodedBytes;
use uucore::i18n::{UEncoding, get_locale_encoding};
use uucore::i18n::UEncoding;

let encoding = get_locale_encoding();
let encoding = uucore::i18n::get_locale_encoding();

// For pattern processing, we need to handle it based on locale
let pattern_str = String::from_utf8(pattern_bytes.clone())
Expand Down Expand Up @@ -388,9 +388,9 @@ fn regex_search<T: onig::EncodedChars>(
/// Find matches in the input using the compiled regex
fn find_match(regex: Regex, re_string: String, left_bytes: Vec<u8>) -> String {
use onig::EncodedBytes;
use uucore::i18n::{UEncoding, get_locale_encoding};
use uucore::i18n::UEncoding;

let encoding = get_locale_encoding();
let encoding = uucore::i18n::get_locale_encoding();

// Match against the input using the appropriate encoding
let mut region = onig::Region::new();
Expand Down Expand Up @@ -506,11 +506,12 @@ fn find_match(regex: Regex, re_string: String, left_bytes: Vec<u8>) -> String {

/// Evaluate a match expression with locale-aware regex matching
fn evaluate_match_expression(left_bytes: Vec<u8>, right_bytes: Vec<u8>) -> ExprResult<NumOrStr> {
use uucore::i18n::UEncoding;

let (regex, re_string) = build_regex(right_bytes)?;

// Special case for ASCII locale with capture groups that need to return raw bytes
use uucore::i18n::{UEncoding, get_locale_encoding};
let encoding = get_locale_encoding();
let encoding = uucore::i18n::get_locale_encoding();

if matches!(encoding, UEncoding::Ascii) && regex.captures_len() > 0 {
// Try to find the actual capture bytes for ASCII locale
Expand Down
10 changes: 6 additions & 4 deletions src/uu/mknod/src/mknod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,28 +98,30 @@ fn mknod(file_name: &str, config: Config) -> i32 {
// Apply SELinux context if requested
#[cfg(feature = "selinux")]
if config.set_security_context {
use std::io::Write as _;

if let Err(e) = uucore::selinux::set_selinux_security_context(
std::path::Path::new(file_name),
config.context.as_ref(),
) {
// if it fails, delete the file
let _ = std::fs::remove_file(file_name);
use std::io::{Write, stderr};
let _ = writeln!(stderr(), "mknod: {e}");
let _ = writeln!(std::io::stderr(), "mknod: {e}");
return 1;
}
}

// Apply SMACK context if requested
#[cfg(feature = "smack")]
if config.set_security_context {
use std::io::Write as _;

if let Err(e) =
uucore::smack::set_smack_label_and_cleanup(file_name, config.context.as_ref(), |p| {
std::fs::remove_file(p)
})
{
use std::io::{Write, stderr};
let _ = writeln!(stderr(), "mknod: {e}");
let _ = writeln!(std::io::stderr(), "mknod: {e}");
return 1;
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/uu/sort/src/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ fn parse_lines<'a>(
separator: u8,
settings: &GlobalSettings,
) {
const SMALL_CHUNK_BYTES: usize = 64 * 1024;

let read = read.strip_suffix(&[separator]).unwrap_or(read);

assert!(lines.is_empty());
Expand All @@ -279,7 +281,6 @@ fn parse_lines<'a>(
assert!(line_data.collation_key_buffer.is_empty());
assert!(line_data.collation_key_ends.is_empty());
token_buffer.clear();
const SMALL_CHUNK_BYTES: usize = 64 * 1024;
let mut estimated = (*line_count_hint).max(1);
let mut exact_line_count = None;
if *line_count_hint == 0 || read.len() <= SMALL_CHUNK_BYTES {
Expand Down
5 changes: 3 additions & 2 deletions src/uu/sort/src/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2834,11 +2834,12 @@ fn ascii_case_insensitive_cmp(a: &[u8], b: &[u8]) -> Ordering {
// For example, 5e10KFD would be 5e10 or 5x10^10 and +10000HFKJFK would become 10000.
#[allow(clippy::cognitive_complexity)]
fn get_leading_gen(inp: &[u8], decimal_pt: u8) -> Range<usize> {
// check for inf, -inf and nan
const ALLOWED_PREFIXES: &[&[u8]] = &[b"inf", b"-inf", b"nan"];

let trimmed = inp.trim_ascii_start();
let leading_whitespace_len = inp.len() - trimmed.len();

// check for inf, -inf and nan
const ALLOWED_PREFIXES: &[&[u8]] = &[b"inf", b"-inf", b"nan"];
for &allowed_prefix in ALLOWED_PREFIXES {
if trimmed.len() >= allowed_prefix.len()
&& trimmed[..allowed_prefix.len()].eq_ignore_ascii_case(allowed_prefix)
Expand Down
4 changes: 2 additions & 2 deletions src/uu/stdbuf/src/stdbuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,12 @@ fn get_preload_env(tmp_dir: &TempDir) -> UResult<(String, PathBuf)> {

#[cfg(feature = "feat_external_libstdbuf")]
fn get_preload_env(_tmp_dir: &TempDir) -> UResult<(String, PathBuf)> {
let (preload, extension) = preload_strings();

// Use the directory provided at compile time via LIBSTDBUF_DIR environment variable
// This will fail to compile if LIBSTDBUF_DIR is not set, which is the desired behavior
const LIBSTDBUF_DIR: &str = env!("LIBSTDBUF_DIR");

let (preload, extension) = preload_strings();

// Search paths in order:
// 1. Directory where stdbuf is located (program_path)
// 2. Compile-time directory from LIBSTDBUF_DIR
Expand Down
3 changes: 1 addition & 2 deletions src/uu/wc/src/utf8/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,7 @@ impl<B: BufRead> BufReadDecoder<B> {
let buf = try_io!(self.buf_read.fill_buf());

// Force loop iteration to go through an explicit `continue`
enum Unreachable {}
let _: Unreachable = if self.incomplete.is_empty() {
let _: std::convert::Infallible = if self.incomplete.is_empty() {
if buf.is_empty() {
return None; // EOF
}
Expand Down
12 changes: 7 additions & 5 deletions src/uucore/src/lib/features/checksum/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,17 @@ impl LineFormat {
///
/// [tagged output format]: https://www.gnu.org/software/coreutils/manual/html_node/cksum-output-modes.html#cksum-output-modes-1
fn parse_algo_based(line: &[u8]) -> Option<LineInfo> {
enum SubCase {
Posix,
OpenSSL,
}

// r"\MD5 (a\\ b) = abc123",
// BLAKE2b(44)= a45a4c4883cce4b50d844fab460414cc2080ca83690e74d850a9253e757384366382625b218c8585daee80f34dc9eb2f2fde5fb959db81cd48837f9216e7b0fa
let trimmed = line.trim_ascii_start();
let algo_start = usize::from(trimmed.starts_with(b"\\"));
let rest = &trimmed[algo_start..];

enum SubCase {
Posix,
OpenSSL,
}
// find the next parenthesis using byte search (not next whitespace) because openssl's
// tagged format does not put a space before (filename)

Expand Down Expand Up @@ -858,6 +859,8 @@ fn process_checksum_file(
cli_algo_length: Option<usize>,
opts: ChecksumValidateOptions,
) -> Result<(), FileCheckError> {
use LineCheckError::*;

let mut res = ChecksumResult::default();

let input_is_stdin = filename_input == OsStr::new("-");
Expand Down Expand Up @@ -906,7 +909,6 @@ fn process_checksum_file(

// Match a first time to elude critical UErrors, and increment the total
// in all cases except on skipped.
use LineCheckError::*;
match line_result {
Err(UError(e)) => return Err(e.into()),
Err(Skipped) => (),
Expand Down
4 changes: 2 additions & 2 deletions src/uucore/src/lib/features/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,12 +567,12 @@ impl SupportsFastDecodeAndEncode for Base32Wrapper {
}

fn pad_remainder(&self, remainder: &[u8]) -> Option<PadResult> {
const VALID_REMAINDERS: [usize; 4] = [2, 4, 5, 7];

if remainder.is_empty() || remainder.contains(&b'=') {
return None;
}

const VALID_REMAINDERS: [usize; 4] = [2, 4, 5, 7];

let mut len = remainder.len();
let mut trimmed = false;

Expand Down
5 changes: 3 additions & 2 deletions src/uucore/src/lib/features/format/num_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,9 @@ fn format_float_hexadecimal(
case: Case,
force_decimal: ForceDecimal,
) -> String {
// TODO: Make this configurable? e.g. arm64 only displays 1 digit.
const BEFORE_BITS: usize = 4;

debug_assert!(!bd.is_negative());
// Default precision for %a is supposed to be sufficient to represent the
// exact value. This is platform specific, GNU coreutils uses a `long double`,
Expand Down Expand Up @@ -611,8 +614,6 @@ fn format_float_hexadecimal(

// Emulate x86(-64) behavior, we display 4 binary digits before the decimal point,
// so the value will always be between 0x8 and 0xf.
// TODO: Make this configurable? e.g. arm64 only displays 1 digit.
const BEFORE_BITS: usize = 4;
let wanted_bits = (BEFORE_BITS + max_precision * 4) as u64;
let bits = frac2.bits();

Expand Down
4 changes: 2 additions & 2 deletions src/uucore/src/lib/features/parser/num_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,15 +348,15 @@ fn parse_special_value(
negative: bool,
allowed_suffixes: &[(char, u32)],
) -> Result<ExtendedBigDecimal, ExtendedParserError<ExtendedBigDecimal>> {
let input_lc = input.to_ascii_lowercase();

// Array of ("String to match", return value when sign positive, when sign negative)
const MATCH_TABLE: &[(&str, ExtendedBigDecimal)] = &[
("infinity", ExtendedBigDecimal::Infinity),
("inf", ExtendedBigDecimal::Infinity),
("nan", ExtendedBigDecimal::Nan),
];

let input_lc = input.to_ascii_lowercase();

for (str, ebd) in MATCH_TABLE {
if input_lc.starts_with(str) {
let mut special = ebd.clone();
Expand Down
3 changes: 2 additions & 1 deletion src/uucore/src/lib/features/parser/parse_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ use std::time::Duration;
/// assert!(from_str("2d", false).is_err());
/// ```
pub fn from_str(string: &str, allow_suffixes: bool) -> Result<Duration, String> {
const NANOS_PER_SEC: u32 = 1_000_000_000;

// TODO: Switch to Duration::NANOSECOND if that ever becomes stable
// https://github.com/rust-lang/rust/issues/57391
const NANOSECOND_DURATION: Duration = Duration::from_nanos(1);
Expand Down Expand Up @@ -105,7 +107,6 @@ pub fn from_str(string: &str, allow_suffixes: bool) -> Result<Duration, String>
return Ok(NANOSECOND_DURATION);
}

const NANOS_PER_SEC: u32 = 1_000_000_000;
let whole_secs: u64 = match (&nanos_bi / NANOS_PER_SEC).try_into() {
Ok(whole_secs) => whole_secs,
Err(_) => return Ok(Duration::MAX),
Expand Down
Loading
Loading