Skip to content
6 changes: 5 additions & 1 deletion src/uu/cp/src/cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
#[cfg(unix)]
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf, StripPrefixError};
use std::sync::LazyLock;
use std::{fmt, io};
#[cfg(all(unix, not(target_os = "android")))]
use uucore::fsxattr::{copy_xattrs, copy_xattrs_skip_selinux};
Expand Down Expand Up @@ -2449,7 +2450,7 @@ fn copy_file(
OverwriteMode::Clobber(ClobberMode::RemoveDestination)
)
&& !is_symlink_loop(dest)
&& std::env::var_os("POSIXLY_CORRECT").is_none()
&& !*IS_POSIXLY_CORRECT
{
return Err(CpError::Error(
translate!("cp-error-not-writing-dangling-symlink", "dest" => dest.quote()),
Expand Down Expand Up @@ -2903,6 +2904,9 @@ fn disk_usage_directory(p: &Path) -> io::Result<u64> {
Ok(total)
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("POSIXLY_CORRECT").is_some());

#[cfg(test)]
mod tests {

Expand Down
11 changes: 0 additions & 11 deletions src/uu/df/src/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,6 @@ impl fmt::Display for BlockSize {

#[cfg(test)]
mod tests {

use std::env;

use crate::blocks::{BlockSize, SuffixType, to_magnitude_and_suffix};

#[test]
Expand Down Expand Up @@ -367,12 +364,4 @@ mod tests {
assert_eq!(format!("{}", BlockSize::Bytes(1000 * 1024)), "1.1MB");
assert_eq!(format!("{}", BlockSize::Bytes(1_000_000_000_000)), "1.0TB");
}

#[test]
fn test_default_block_size() {
assert_eq!(BlockSize::Bytes(1024), BlockSize::default());
unsafe { env::set_var("POSIXLY_CORRECT", "1") };
assert_eq!(BlockSize::Bytes(512), BlockSize::default());
unsafe { env::remove_var("POSIXLY_CORRECT") };
}
}
7 changes: 5 additions & 2 deletions src/uu/echo/src/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use clap::{Arg, ArgAction, Command};
use std::env;
use std::ffi::{OsStr, OsString};
use std::io::{StdoutLock, Write, stdout};
use std::sync::LazyLock;
use uucore::error::UResult;
use uucore::format::{FormatChar, OctalParsing, parse_escape_only};
use uucore::{crate_version, format_usage, os_str_as_bytes};
Expand Down Expand Up @@ -135,9 +136,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// > escapes are always enabled. To echo the string ‘-n’, one of the
// > characters can be escaped in either octal or hexadecimal
// > representation. For example, echo -e '\x2dn'.
let is_posixly_correct = env::var_os("POSIXLY_CORRECT").is_some();

let (args, options): (Box<dyn Iterator<Item = OsString>>, Options) = if is_posixly_correct {
let (args, options): (Box<dyn Iterator<Item = OsString>>, Options) = if *IS_POSIXLY_CORRECT {
if args.peek().is_some_and(|arg| arg == "-n") {
// if POSIXLY_CORRECT is set and the first argument is the "-n" flag
// we filter flags normally but 'escaped' is activated nonetheless.
Expand Down Expand Up @@ -254,3 +254,6 @@ fn execute(

Ok(())
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| env::var_os("POSIXLY_CORRECT").is_some());
14 changes: 6 additions & 8 deletions src/uu/id/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
use clap::{Arg, ArgAction, Command};
use std::ffi::CStr;
use std::io::{self, Write};
use std::sync::LazyLock;
use uucore::display::Quotable;
use uucore::entries::{self, Group, Locate, Passwd};
use uucore::error::UResult;
Expand Down Expand Up @@ -706,10 +707,7 @@ fn id_print(state: &State, groups: &[u32]) -> io::Result<()> {
)?;

#[cfg(feature = "selinux")]
if state.selinux_supported
&& !state.user_specified
&& std::env::var_os("POSIXLY_CORRECT").is_none()
{
if state.selinux_supported && !state.user_specified && !*IS_POSIXLY_CORRECT {
// print SElinux context (does not depend on "-Z")
if let Ok(context) = selinux::SecurityContext::current(false) {
let bytes = context.as_bytes();
Expand All @@ -718,10 +716,7 @@ fn id_print(state: &State, groups: &[u32]) -> io::Result<()> {
}

#[cfg(feature = "smack")]
if state.smack_supported
&& !state.user_specified
&& std::env::var_os("POSIXLY_CORRECT").is_none()
{
if state.smack_supported && !state.user_specified && !*IS_POSIXLY_CORRECT {
// print SMACK label (does not depend on "-Z")
if let Ok(label) = uucore::smack::get_smack_label_for_self() {
write!(lock, " context={label}")?;
Expand All @@ -731,6 +726,9 @@ fn id_print(state: &State, groups: &[u32]) -> io::Result<()> {
Ok(())
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("POSIXLY_CORRECT").is_some());

#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "openbsd")))]
mod audit {
use super::libc::{c_int, c_uint, dev_t, pid_t, uid_t};
Expand Down
6 changes: 5 additions & 1 deletion src/uu/ls/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::{
ffi::{OsStr, OsString},
io::{IsTerminal, stdout},
num::IntErrorKind,
sync::LazyLock,
};

use glob::Pattern;
Expand Down Expand Up @@ -156,7 +157,7 @@ fn resolve_block_sizes_from_env(opt_kb: bool) -> (u64, u64) {
(DEFAULT_FILE_SIZE_BLOCK_SIZE, DEFAULT_BLOCK_SIZE)
}
parse_block_size::BlockSizeEnv::NotSet => {
if std::env::var_os("POSIXLY_CORRECT").is_some() && !opt_kb {
if *IS_POSIXLY_CORRECT && !opt_kb {
(DEFAULT_FILE_SIZE_BLOCK_SIZE, POSIXLY_CORRECT_BLOCK_SIZE)
} else {
(DEFAULT_FILE_SIZE_BLOCK_SIZE, DEFAULT_BLOCK_SIZE)
Expand All @@ -167,6 +168,9 @@ fn resolve_block_sizes_from_env(opt_kb: bool) -> (u64, u64) {
}
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("POSIXLY_CORRECT").is_some());

pub(crate) enum Dereference {
None,
DirArgs,
Expand Down
6 changes: 5 additions & 1 deletion src/uu/mktemp/src/mktemp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use std::path::{MAIN_SEPARATOR, Path, PathBuf};
use std::fs;
#[cfg(unix)]
use std::os::unix::prelude::PermissionsExt;
use std::sync::LazyLock;

use rand::{
RngExt as _, SeedableRng as _,
Expand Down Expand Up @@ -395,7 +396,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// application logic.
let options = Options::from(&matches);

if env::var_os("POSIXLY_CORRECT").is_some() {
if *IS_POSIXLY_CORRECT {
// If POSIXLY_CORRECT was set, template MUST be the last argument.
if matches.contains_id(ARG_TEMPLATE) {
// Template argument was provided, check if was the last one.
Expand Down Expand Up @@ -648,6 +649,9 @@ pub fn mktemp(options: &Options) -> UResult<PathBuf> {
}
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| env::var_os("POSIXLY_CORRECT").is_some());

#[cfg(test)]
mod tests {
use crate::find_last_contiguous_block_of_xs as findxs;
Expand Down
5 changes: 4 additions & 1 deletion src/uu/nohup/src/nohup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,16 @@ impl UError for NohupError {
}

static FAILURE_CODE: LazyLock<i32> = LazyLock::new(|| {
if env::var_os("POSIXLY_CORRECT").is_some() {
if *IS_POSIXLY_CORRECT {
POSIX_NOHUP_FAILURE
} else {
EXIT_CANCELED
}
});

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| env::var_os("POSIXLY_CORRECT").is_some());

#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uucore::clap_localization::handle_clap_result_with_exit_code(
Expand Down
6 changes: 5 additions & 1 deletion src/uu/pr/src/pr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::fs::metadata;
use std::io::{Read, Write, stderr, stdin, stdout};
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use std::sync::LazyLock;
use std::time::SystemTime;
use thiserror::Error;

Expand Down Expand Up @@ -489,7 +490,7 @@ fn get_date_format(matches: &ArgMatches) -> String {
Some(format) => format,
None => {
// Replicate behavior from GNU manual.
if std::env::var("POSIXLY_CORRECT").is_ok()
if *IS_POSIXLY_CORRECT
// TODO: This needs to be moved to uucore and handled by icu?
&& (std::env::var_os("LC_TIME").as_deref() == Some(OsStr::new("POSIX"))
|| std::env::var_os("LC_ALL").as_deref() == Some(OsStr::new("POSIX")))
Expand Down Expand Up @@ -1426,3 +1427,6 @@ fn lines_to_read_for_page(opts: &OutputOptions) -> usize {
fn get_columns(opts: &OutputOptions) -> usize {
opts.column_mode_options.as_ref().map_or(1, |i| i.columns)
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("POSIXLY_CORRECT").is_some());
6 changes: 5 additions & 1 deletion src/uu/pwd/src/pwd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use clap::{Arg, Command};
use std::env;
use std::io;
use std::path::PathBuf;
use std::sync::LazyLock;
use uucore::format_usage;

use uucore::display::println_verbatim;
Expand Down Expand Up @@ -115,7 +116,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// We should get c in this case instead of a/b at the end of the path
let cwd = if matches.get_flag(OPT_PHYSICAL) {
physical_path()
} else if matches.get_flag(OPT_LOGICAL) || env::var("POSIXLY_CORRECT").is_ok() {
} else if matches.get_flag(OPT_LOGICAL) || *IS_POSIXLY_CORRECT {
logical_path()
} else {
physical_path()
Expand Down Expand Up @@ -161,3 +162,6 @@ pub fn uu_app() -> Command {
.action(ArgAction::SetTrue),
)
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| env::var_os("POSIXLY_CORRECT").is_some());
6 changes: 5 additions & 1 deletion src/uu/readlink/src/readlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::ffi::OsString;
use std::fs;
use std::io::{Write, stdout};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use uucore::display::Quotable;
use uucore::error::{FromIo, UResult, UUsageError};
use uucore::fs::{MissingHandling, ResolveMode, canonicalize};
Expand All @@ -36,7 +37,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {

let mut no_trailing_delimiter = matches.get_flag(OPT_NO_NEWLINE);
let use_zero = matches.get_flag(OPT_ZERO);
let verbose = matches.get_flag(OPT_VERBOSE) || env::var("POSIXLY_CORRECT").is_ok();
let verbose = matches.get_flag(OPT_VERBOSE) || *IS_POSIXLY_CORRECT;

// GNU readlink -f/-e/-m follows symlinks first and then applies `..` (physical resolution).
// ResolveMode::Logical collapses `..` before following links, which yields the opposite order,
Expand Down Expand Up @@ -192,3 +193,6 @@ fn show(path: &Path, line_ending: Option<LineEnding>) -> std::io::Result<()> {
}
stdout().flush()
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| env::var_os("POSIXLY_CORRECT").is_some());
41 changes: 6 additions & 35 deletions src/uucore/src/lib/features/parser/parse_block_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
//! for resolving block sizes from environment variables and defaults.
//! This module centralizes that logic.

use std::sync::LazyLock;

use super::parse_size::parse_size_non_zero_u64;

/// Result of looking up a block size from environment variables.
Expand Down Expand Up @@ -66,13 +68,12 @@ pub fn block_size_from_env(vars: &[&str]) -> BlockSizeEnv {
///
/// Returns 512 if `POSIXLY_CORRECT` is set, 1024 otherwise.
pub fn default_block_size() -> u64 {
if std::env::var("POSIXLY_CORRECT").is_ok() {
512
} else {
1024
}
if *IS_POSIXLY_CORRECT { 512 } else { 1024 }
}

static IS_POSIXLY_CORRECT: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("POSIXLY_CORRECT").is_some());

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -344,34 +345,4 @@ mod tests {

clear_env_vars(&["BLOCKSIZE"]);
}

#[test]
fn test_default_block_size_without_posixly_correct() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env_vars(&["POSIXLY_CORRECT"]);
assert_eq!(default_block_size(), 1024);
}

#[test]
fn test_default_block_size_with_posixly_correct() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env_vars(&["POSIXLY_CORRECT"]);

set_env_var("POSIXLY_CORRECT", "1");
assert_eq!(default_block_size(), 512);

clear_env_vars(&["POSIXLY_CORRECT"]);
}

#[test]
fn test_default_block_size_with_posixly_correct_empty() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env_vars(&["POSIXLY_CORRECT"]);

// Even an empty value means POSIXLY_CORRECT is set
set_env_var("POSIXLY_CORRECT", "");
assert_eq!(default_block_size(), 512);

clear_env_vars(&["POSIXLY_CORRECT"]);
}
}
Loading