diff --git a/.github/workflows/TestingCI.yml b/.github/workflows/TestingCI.yml index ad4ccb586..4a24415fb 100644 --- a/.github/workflows/TestingCI.yml +++ b/.github/workflows/TestingCI.yml @@ -15,7 +15,7 @@ jobs: - name: Fetch run: cargo fetch - name: Build - run: cargo build --release --verbose + run: RUSTFLAGS='-D warnings' cargo build --release --verbose - name: Run tests run: cargo test --release --verbose - name: Run fmt check @@ -42,6 +42,6 @@ jobs: - name: Fetch run: cargo fetch - name: Build - run: cargo build --release --verbose + run: RUSTFLAGS='-D warnings' cargo build --release --verbose - name: Run tests run: cargo test --release --verbose diff --git a/Cargo.lock b/Cargo.lock index 7bd5e1498..4330a37d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -133,9 +133,9 @@ dependencies = [ [[package]] name = "bindgen" -version = "0.70.1" +version = "0.71.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" dependencies = [ "bitflags 2.9.0", "cexpr", @@ -146,7 +146,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "rustc-hash", + "rustc-hash 2.1.1", "shlex", "syn 2.0.100", ] @@ -1863,7 +1863,7 @@ checksum = "0a542b0253fa46e632d27a1dc5cf7b930de4df8659dc6e720b647fc72147ae3d" dependencies = [ "countme", "hashbrown 0.14.5", - "rustc-hash", + "rustc-hash 1.1.0", "text-size", ] @@ -1873,6 +1873,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + [[package]] name = "rustix" version = "1.0.3" diff --git a/Cargo.toml b/Cargo.toml index d1412a65c..b9fb154f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ members = [ [workspace.package] repository = "https://github.com/rustcoreutils/posixutils-rs" license = "MIT" -edition = "2021" -rust-version = "1.84.0" +edition = "2024" +rust-version = "1.85.0" [workspace.dependencies] clap = { version = "4", default-features = false, features = ["std", "derive", "help", "usage", "error-context", "cargo"] } @@ -44,5 +44,5 @@ gettext-rs = { path = "./gettext-rs" } errno = "0.3" chrono-tz = "0.10" -[workspace.lints] - +[workspace.lints.rust] +rust-2024-compatibility = "warn" diff --git a/awk/compiler.rs b/awk/compiler.rs index 4f6c2e38f..19c2d9565 100644 --- a/awk/compiler.rs +++ b/awk/compiler.rs @@ -15,10 +15,10 @@ use crate::program::{ }; use crate::regex::Regex; +use pest::Parser; use pest::error::InputLocation; use pest::iterators::{Pair, Pairs}; use pest::pratt_parser::{Assoc, Op, PrattParser}; -use pest::Parser; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::ffi::CString; @@ -704,13 +704,13 @@ impl Compiler { return Err(pest_error_from_span( span, format!("'{}' is not a function", name), - )) + )); } None => { return Err(pest_error_from_span( span, format!("call to undefined function '{}'", name), - )) + )); } } Ok(Expr::new(ExprKind::Number, instructions)) diff --git a/awk/interpreter/array.rs b/awk/interpreter/array.rs index 07b91d4f4..60dd8a784 100644 --- a/awk/interpreter/array.rs +++ b/awk/interpreter/array.rs @@ -8,7 +8,7 @@ // use std::{ - collections::{hash_map::Entry, HashMap}, + collections::{HashMap, hash_map::Entry}, rc::Rc, }; diff --git a/awk/interpreter/io.rs b/awk/interpreter/io.rs index da70f376c..2f20c6d71 100644 --- a/awk/interpreter/io.rs +++ b/awk/interpreter/io.rs @@ -9,7 +9,7 @@ use core::panic; use std::{ - collections::{hash_map::Entry, HashMap}, + collections::{HashMap, hash_map::Entry}, ffi::CString, fs::File, io::{BufReader, Bytes, Read, Write}, @@ -43,13 +43,13 @@ impl TryFrom for RecordSeparator { type ReadResult = Result; macro_rules! read_iter_next { - ($iter:expr, $ret:expr) => { + ($iter:expr_2021, $ret:expr_2021) => { match $iter.next() { Some(byte_result) => byte_result?, None => return $ret, } }; - ($iter:expr) => { + ($iter:expr_2021) => { read_iter_next!($iter, Ok(None)) }; } diff --git a/awk/interpreter/mod.rs b/awk/interpreter/mod.rs index e5fbb478b..f3e4d0ca5 100644 --- a/awk/interpreter/mod.rs +++ b/awk/interpreter/mod.rs @@ -23,9 +23,9 @@ use crate::program::{ }; use crate::regex::Regex; use format::{ - fmt_write_decimal_float, fmt_write_float_general, fmt_write_hex_float, + IntegerFormat, fmt_write_decimal_float, fmt_write_float_general, fmt_write_hex_float, fmt_write_scientific_float, fmt_write_signed, fmt_write_string, fmt_write_unsigned, - parse_conversion_specifier_args, IntegerFormat, + parse_conversion_specifier_args, }; use std::cell::{RefCell, UnsafeCell}; use std::collections::HashMap; @@ -44,11 +44,7 @@ mod string; const STACK_SIZE: usize = 2048; fn bool_to_f64(p: bool) -> f64 { - if p { - 1.0 - } else { - 0.0 - } + if p { 1.0 } else { 0.0 } } fn strtod(s: &str) -> f64 { @@ -410,7 +406,7 @@ fn call_simple_builtin( stack.push_value(value.to_uppercase())?; } BuiltinFunction::Gsub | BuiltinFunction::Sub => { - return builtin_gsub(stack, global_env, function == BuiltinFunction::Sub) + return builtin_gsub(stack, global_env, function == BuiltinFunction::Sub); } BuiltinFunction::System => { let command: CString = stack @@ -588,61 +584,65 @@ impl Record { last_field: usize, truncate_fields: bool, ) -> Result<(), String> { - let last_field = if truncate_fields { - if last_field < *self.last_field.borrow() { - for field in self - .fields - .iter() - .skip(last_field + 1) - .take(*self.last_field.borrow() - last_field) - { - (*field.get()).value = AwkValueVariant::UninitializedScalar; + unsafe { + let last_field = if truncate_fields { + if last_field < *self.last_field.borrow() { + for field in self + .fields + .iter() + .skip(last_field + 1) + .take(*self.last_field.borrow() - last_field) + { + (*field.get()).value = AwkValueVariant::UninitializedScalar; + } } + last_field + } else { + self.last_field.borrow().max(last_field) + }; + let mut new_record = String::new(); + for field in self.fields.iter().skip(1).take(last_field - 1) { + let field_str = (*field.get()) + .clone() + .scalar_to_string(&global_env.convfmt)?; + write!(new_record, "{}{}", field_str, &global_env.ofs) + .expect("error writing to string"); } - last_field - } else { - self.last_field.borrow().max(last_field) - }; - let mut new_record = String::new(); - for field in self.fields.iter().skip(1).take(last_field - 1) { - let field_str = (*field.get()) + let last_field_str = (*self.fields[last_field].get()) .clone() .scalar_to_string(&global_env.convfmt)?; - write!(new_record, "{}{}", field_str, &global_env.ofs) - .expect("error writing to string"); - } - let last_field_str = (*self.fields[last_field].get()) - .clone() - .scalar_to_string(&global_env.convfmt)?; - write!(new_record, "{}", last_field_str).expect("error writing to string"); - // the spec doesn't specify if a recomputed record should be a numeric string. - // Most other implementations don't really handle this case. Here we just - // mark it as a numeric string if appropriate - let record_str = maybe_numeric_string(new_record); - *self.fields[0].get() = AwkValue::field_ref(record_str.clone(), 0); - *self.record.borrow_mut() = record_str.try_into()?; - *self.last_field.borrow_mut() = last_field; - Ok(()) + write!(new_record, "{}", last_field_str).expect("error writing to string"); + // the spec doesn't specify if a recomputed record should be a numeric string. + // Most other implementations don't really handle this case. Here we just + // mark it as a numeric string if appropriate + let record_str = maybe_numeric_string(new_record); + *self.fields[0].get() = AwkValue::field_ref(record_str.clone(), 0); + *self.record.borrow_mut() = record_str.try_into()?; + *self.last_field.borrow_mut() = last_field; + Ok(()) + } } /// # Safety /// The caller has to ensure that there are no active references to the fields unsafe fn recompute_fields(&self, global_env: &GlobalEnv) -> Result<(), String> { - let mut last_field = 0; - let record_str = (*self.fields[0].get()) - .to_owned() - .scalar_to_string(&global_env.convfmt)?; - split_record(record_str.clone(), &global_env.fs, |i, s| { - let field_index = i + 1; - last_field += 1; - *self.fields[field_index].get() = AwkValue::field_ref(s, field_index as u16); + unsafe { + let mut last_field = 0; + let record_str = (*self.fields[0].get()) + .to_owned() + .scalar_to_string(&global_env.convfmt)?; + split_record(record_str.clone(), &global_env.fs, |i, s| { + let field_index = i + 1; + last_field += 1; + *self.fields[field_index].get() = AwkValue::field_ref(s, field_index as u16); + Ok(()) + }) + .expect("error splitting record"); + *self.fields[0].get() = AwkValue::field_ref(record_str.clone(), 0); + *self.record.borrow_mut() = record_str.try_into()?; + *self.last_field.borrow_mut() = last_field; Ok(()) - }) - .expect("error splitting record"); - *self.fields[0].get() = AwkValue::field_ref(record_str.clone(), 0); - *self.record.borrow_mut() = record_str.try_into()?; - *self.last_field.borrow_mut() = last_field; - Ok(()) + } } fn get_last_field(&self) -> usize { @@ -920,16 +920,18 @@ impl StackValue { /// # Safety /// the caller has to ensure that the value is valid and dereferencable unsafe fn value_ref(&mut self) -> &mut AwkValue { - match self { - StackValue::Value(val) => val.get_mut(), - StackValue::ValueRef(val_ref) => &mut **val_ref, - StackValue::UninitializedRef(val_ref) => &mut **val_ref, - StackValue::ArrayElementRef(array_element_ref) => (*array_element_ref.array) - .as_array() - .expect("expected array") - .index_to_value(array_element_ref.value_index) - .expect("invalid array value index"), - _ => unreachable!("invalid stack value"), + unsafe { + match self { + StackValue::Value(val) => val.get_mut(), + StackValue::ValueRef(val_ref) => &mut **val_ref, + StackValue::UninitializedRef(val_ref) => &mut **val_ref, + StackValue::ArrayElementRef(array_element_ref) => (*array_element_ref.array) + .as_array() + .expect("expected array") + .index_to_value(array_element_ref.value_index) + .expect("invalid array value index"), + _ => unreachable!("invalid stack value"), + } } } @@ -962,29 +964,33 @@ impl StackValue { /// # Safety /// pointers inside the `StackValue` have to be valid and dereferencable unsafe fn into_owned(self) -> AwkValue { - match self { - StackValue::Value(val) => val.into_inner(), - StackValue::ValueRef(ref_val) => (*ref_val).clone().into_ref(AwkRefType::None), - StackValue::UninitializedRef(_) => AwkValue::uninitialized_scalar(), - _ => unreachable!("invalid stack value"), + unsafe { + match self { + StackValue::Value(val) => val.into_inner(), + StackValue::ValueRef(ref_val) => (*ref_val).clone().into_ref(AwkRefType::None), + StackValue::UninitializedRef(_) => AwkValue::uninitialized_scalar(), + _ => unreachable!("invalid stack value"), + } } } /// # Safety /// pointers inside the `StackValue` have to be valid and dereferencable unsafe fn ensure_value_is_scalar(&mut self) -> Result<(), String> { - self.value_ref().ensure_value_is_scalar() + unsafe { self.value_ref().ensure_value_is_scalar() } } /// # Safety /// `value` has to be a valid pointer at least until the value preceding it /// on the stack is popped unsafe fn from_var(value: *mut AwkValue) -> Self { - let value_ref = &mut *value; - match value_ref.value { - AwkValueVariant::Array(_) => StackValue::ValueRef(value), - AwkValueVariant::Uninitialized => StackValue::UninitializedRef(value), - _ => StackValue::Value(UnsafeCell::new(value_ref.clone())), + unsafe { + let value_ref = &mut *value; + match value_ref.value { + AwkValueVariant::Array(_) => StackValue::ValueRef(value), + AwkValueVariant::Uninitialized => StackValue::UninitializedRef(value), + _ => StackValue::Value(UnsafeCell::new(value_ref.clone())), + } } } @@ -1061,12 +1067,14 @@ impl<'i, 's> Stack<'i, 's> { /// # Safety /// `value` has to be valid at least until the value preceding it is popped unsafe fn push(&mut self, value: StackValue) -> Result<(), String> { - if self.sp == self.stack_end { - Err("stack overflow".to_string()) - } else { - *self.sp = value; - self.sp = self.sp.add(1); - Ok(()) + unsafe { + if self.sp == self.stack_end { + Err("stack overflow".to_string()) + } else { + *self.sp = value; + self.sp = self.sp.add(1); + Ok(()) + } } } @@ -1116,7 +1124,7 @@ impl<'i, 's> Stack<'i, 's> { /// `value_ptr` has to be safe to access at least until the value preceding it /// on the stack is popped. unsafe fn push_ref(&mut self, value_ptr: *mut AwkValue) -> Result<(), String> { - self.push(StackValue::ValueRef(value_ptr)) + unsafe { self.push(StackValue::ValueRef(value_ptr)) } } fn next_instruction(&mut self) -> Option { @@ -1207,7 +1215,7 @@ struct Interpreter { } macro_rules! numeric_op { - ($stack:expr, $op:tt) => { + ($stack:expr_2021, $op:tt) => { let rhs = $stack.pop_scalar_value()?.scalar_as_f64(); let lhs = $stack.pop_scalar_value()?.scalar_as_f64(); $stack.push_value(lhs $op rhs)?; @@ -1215,7 +1223,7 @@ macro_rules! numeric_op { } macro_rules! compare_op { - ($stack:expr, $convfmt:expr, $op:tt) => { + ($stack:expr_2021, $convfmt:expr_2021, $op:tt) => { let rhs = $stack.pop_scalar_value()?; let lhs = $stack.pop_scalar_value()?; match (&lhs.value, &rhs.value) { diff --git a/awk/main.rs b/awk/main.rs index ee785598c..c2497e48c 100644 --- a/awk/main.rs +++ b/awk/main.rs @@ -11,7 +11,7 @@ use crate::compiler::compile_program; use crate::interpreter::interpret; use clap::Parser; use compiler::SourceFile; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::error::Error; use std::fmt::Display; use std::io::Read; diff --git a/awk/tests/integration.rs b/awk/tests/integration.rs index 831356c88..38afb887e 100644 --- a/awk/tests/integration.rs +++ b/awk/tests/integration.rs @@ -1,4 +1,4 @@ -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; fn test_awk(args: Vec, expected_output: &str) { run_test(TestPlan { @@ -12,7 +12,7 @@ fn test_awk(args: Vec, expected_output: &str) { } macro_rules! test_awk { - ($test_name:ident $(,$data_file:expr)*) => { + ($test_name:ident $(,$data_file:expr_2021)*) => { test_awk(vec![ "-f".to_string(), concat!("tests/awk/", stringify!($test_name), ".awk").to_string(), diff --git a/calc/bc.rs b/calc/bc.rs index 399ff3a01..2736aff14 100644 --- a/calc/bc.rs +++ b/calc/bc.rs @@ -15,8 +15,8 @@ use bc_util::{ }; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use rustyline::{error::ReadlineError, DefaultEditor, Result}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; +use rustyline::{DefaultEditor, Result, error::ReadlineError}; mod bc_util; diff --git a/calc/bc_util/number.rs b/calc/bc_util/number.rs index e18007409..b801f6aa7 100644 --- a/calc/bc_util/number.rs +++ b/calc/bc_util/number.rs @@ -1,4 +1,4 @@ -use bigdecimal::{num_bigint::BigInt, BigDecimal, Num, One, Signed, ToPrimitive, Zero}; +use bigdecimal::{BigDecimal, Num, One, Signed, ToPrimitive, Zero, num_bigint::BigInt}; /// Converts a character to a number /// # Panics diff --git a/calc/bc_util/parser.rs b/calc/bc_util/parser.rs index 2764e9706..103838936 100644 --- a/calc/bc_util/parser.rs +++ b/calc/bc_util/parser.rs @@ -552,7 +552,7 @@ fn gather_errors(text: &str, file_path: Option<&str>, first_error: PestError) -> return ParseError { errors, is_incomplete: false, - } + }; } Err(err) => { byte_index += location_end(&err.location); diff --git a/calc/expr.rs b/calc/expr.rs index 58648a769..8e87a5c52 100644 --- a/calc/expr.rs +++ b/calc/expr.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use regex::Regex; #[derive(Clone, Debug, PartialEq)] diff --git a/calc/tests/bc/mod.rs b/calc/tests/bc/mod.rs index b9bf58afc..e4b3a0bbb 100644 --- a/calc/tests/bc/mod.rs +++ b/calc/tests/bc/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn test_bc(program: &str, expected_output: &str) { run_test(TestPlan { diff --git a/calc/tests/expr/mod.rs b/calc/tests/expr/mod.rs index 8cb428c21..33d685549 100644 --- a/calc/tests/expr/mod.rs +++ b/calc/tests/expr/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn expr_test(args: &[&str], expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/clippy.toml b/clippy.toml index 5729b3f05..4972822f1 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1 +1 @@ -msrv = "1.80.0" +msrv = "1.85.0" diff --git a/datetime/cal.rs b/datetime/cal.rs index fdefbe9a5..8dd65e316 100644 --- a/datetime/cal.rs +++ b/datetime/cal.rs @@ -13,7 +13,7 @@ use chrono::Datelike; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command(version, about = gettext("cal - print a calendar"))] diff --git a/datetime/date.rs b/datetime/date.rs index 5ea597de9..a59d18b23 100644 --- a/datetime/date.rs +++ b/datetime/date.rs @@ -13,7 +13,7 @@ use chrono::{DateTime, Datelike, Local, LocalResult, TimeZone, Utc}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; const DEF_TIMESTR: &str = "%a %b %e %H:%M:%S %Z %Y"; diff --git a/datetime/sleep.rs b/datetime/sleep.rs index d9324b8dc..37796cdc1 100644 --- a/datetime/sleep.rs +++ b/datetime/sleep.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::{thread, time}; #[derive(Parser)] diff --git a/datetime/time.rs b/datetime/time.rs index fb62d4dc5..a83873aef 100644 --- a/datetime/time.rs +++ b/datetime/time.rs @@ -13,7 +13,7 @@ use std::time::Instant; use clap::Parser; use gettextrs::{ - bind_textdomain_codeset, bindtextdomain, gettext, setlocale, textdomain, LocaleCategory, + LocaleCategory, bind_textdomain_codeset, bindtextdomain, gettext, setlocale, textdomain, }; #[derive(Parser)] diff --git a/dev/ar.rs b/dev/ar.rs index d1bd164dd..9e0908af0 100644 --- a/dev/ar.rs +++ b/dev/ar.rs @@ -11,7 +11,7 @@ use chrono::DateTime; use clap::{Parser, Subcommand}; use object::{Object, ObjectSymbol, SymbolKind}; use std::ffi::{OsStr, OsString}; -use std::io::{stdout, Write}; +use std::io::{Write, stdout}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::fs::MetadataExt; use std::path::Path; diff --git a/dev/nm.rs b/dev/nm.rs index 02da0b1b1..2048e1f15 100644 --- a/dev/nm.rs +++ b/dev/nm.rs @@ -17,7 +17,7 @@ use object::{ }; use clap::{Parser, ValueEnum}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::collections::HashMap; use std::fs; diff --git a/dev/strings.rs b/dev/strings.rs index a17f38830..c47c933b5 100644 --- a/dev/strings.rs +++ b/dev/strings.rs @@ -10,7 +10,7 @@ use std::ffi::OsString; use clap::{Parser, ValueEnum}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use object::{Object, ObjectSection}; #[derive(Clone, Copy, ValueEnum)] diff --git a/dev/strip.rs b/dev/strip.rs index be1ec6c4c..188332688 100644 --- a/dev/strip.rs +++ b/dev/strip.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use object::{ archive, build::elf::{Builder, Section, SectionData}, diff --git a/dev/tests/dev-tests.rs b/dev/tests/dev-tests.rs index 835d3f302..d7e0d49e0 100644 --- a/dev/tests/dev-tests.rs +++ b/dev/tests/dev-tests.rs @@ -1,5 +1,5 @@ use object::{Object, ObjectSection, ObjectSymbol}; -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; use std::fs; fn ar_compare_test( @@ -542,7 +542,8 @@ fn test_strings_print_multiple() { #[test] fn test_strings_utf8_file() { - std::env::set_var("LC_CTYPE", "UTF-8"); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::set_var("LC_CTYPE", "UTF-8") }; strings_test( &["tests/strings/utf8.bin"], include_str!("strings/utf8.correct.txt"), diff --git a/display/echo.rs b/display/echo.rs index 2b04e9874..1998aae87 100644 --- a/display/echo.rs +++ b/display/echo.rs @@ -13,7 +13,7 @@ // Write an 8-bit value that is the 0, 1, 2 or 3-digit octal number _num_. // -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::io::{self, Write}; fn translate_str(skip_nl: bool, s: &str) -> String { diff --git a/display/more.rs b/display/more.rs index ff6b606ac..797b1d16b 100644 --- a/display/more.rs +++ b/display/more.rs @@ -8,22 +8,22 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use libc::{ - getegid, getgid, getuid, regcomp, regex_t, regexec, setgid, setuid, REG_ICASE, REG_NOMATCH, + REG_ICASE, REG_NOMATCH, getegid, getgid, getuid, regcomp, regex_t, regexec, setgid, setuid, }; use std::collections::HashMap; use std::ffi::CString; use std::fs::File; -use std::io::{stdout, BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write}; +use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write, stdout}; use std::ops::{Not, Range}; use std::os::fd::AsRawFd; use std::path::PathBuf; -use std::process::{exit, ExitStatus}; +use std::process::{ExitStatus, exit}; use std::ptr; use std::str::FromStr; -use std::sync::mpsc::{channel, Receiver, TryRecvError}; use std::sync::Mutex; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; use std::time::Duration; use termion::{clear::*, cursor::*, event::*, input::*, raw::*, screen::*, style::*, *}; diff --git a/display/printf.rs b/display/printf.rs index bb9112952..2a9e7377e 100644 --- a/display/printf.rs +++ b/display/printf.rs @@ -11,7 +11,7 @@ // - fix bug: zero padding does not work for negative numbers // -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::{ error::Error, io::{self, Write}, diff --git a/display/tests/echo/mod.rs b/display/tests/echo/mod.rs index 2a75891fc..531da5b6b 100644 --- a/display/tests/echo/mod.rs +++ b/display/tests/echo/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn echo_test(args: &[&str], expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/display/tests/more/mod.rs b/display/tests/more/mod.rs index a1b3cc149..9830a41ac 100644 --- a/display/tests/more/mod.rs +++ b/display/tests/more/mod.rs @@ -9,7 +9,7 @@ use std::process::Output; -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; fn test_checker_more(plan: &TestPlan, output: &Output) { let stdout = String::from_utf8_lossy(&output.stdout); diff --git a/display/tests/printf/mod.rs b/display/tests/printf/mod.rs index f04cc9602..44a662e8e 100644 --- a/display/tests/printf/mod.rs +++ b/display/tests/printf/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; #[test] fn test_basic_string_output() { diff --git a/file/cat.rs b/file/cat.rs index beba13c15..96d480e13 100644 --- a/file/cat.rs +++ b/file/cat.rs @@ -16,9 +16,9 @@ use std::io::{self, Read, Write}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; #[derive(Parser)] #[command(version, about = gettext("cat - concatenate and print files"))] diff --git a/file/cmp.rs b/file/cmp.rs index a0afa8218..f33e8785e 100644 --- a/file/cmp.rs +++ b/file/cmp.rs @@ -12,7 +12,7 @@ use std::path::PathBuf; use std::process::ExitCode; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::io::input_reader; #[derive(Parser)] diff --git a/file/dd.rs b/file/dd.rs index f50054c2d..540d5f9a0 100644 --- a/file/dd.rs +++ b/file/dd.rs @@ -10,7 +10,7 @@ use std::fs; use std::io::{self, Read, Write}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; const DEF_BLOCK_SIZE: usize = 512; diff --git a/file/file.rs b/file/file.rs index 82bff30de..25c18d859 100644 --- a/file/file.rs +++ b/file/file.rs @@ -15,9 +15,9 @@ use std::path::PathBuf; use std::{fs, io}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; -use crate::magic::{get_type_from_magic_file_dbs, DEFAULT_MAGIC_FILE}; +use crate::magic::{DEFAULT_MAGIC_FILE, get_type_from_magic_file_dbs}; #[derive(Parser)] #[command( diff --git a/file/find.rs b/file/find.rs index 5f6eff109..382538ad9 100644 --- a/file/find.rs +++ b/file/find.rs @@ -12,7 +12,7 @@ use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; use std::path::PathBuf; use std::{env, fs}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use regex::Regex; use walkdir::{DirEntry, WalkDir}; diff --git a/file/od.rs b/file/od.rs index 03452a91c..7709b8a86 100644 --- a/file/od.rs +++ b/file/od.rs @@ -15,7 +15,7 @@ use std::slice::Chunks; use std::str::FromStr; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use crate::io::ErrorKind; diff --git a/file/split.rs b/file/split.rs index c2de348f5..572c089ef 100644 --- a/file/split.rs +++ b/file/split.rs @@ -13,9 +13,9 @@ use std::io::{self, BufRead, Error, ErrorKind, Read, Write}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; -use plib::io::{input_reader, input_stream}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::{input_reader, input_stream}; #[derive(Parser)] #[command(version, about = gettext("split - split a file into pieces"))] @@ -164,7 +164,7 @@ impl OutputState { fn write(&mut self, buf: &[u8]) -> io::Result<()> { match &mut self.outf { - Some(ref mut f) => f.write_all(buf), + Some(f) => f.write_all(buf), // TODO: None => panic!("unreachable"), } diff --git a/file/tee.rs b/file/tee.rs index d50d7af93..0b20be33e 100644 --- a/file/tee.rs +++ b/file/tee.rs @@ -11,7 +11,7 @@ use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::BUFSZ; #[derive(Parser)] diff --git a/file/tests/cmp/mod.rs b/file/tests/cmp/mod.rs index badee5a37..967779e30 100644 --- a/file/tests/cmp/mod.rs +++ b/file/tests/cmp/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn run_test_helper( args: &[&str], diff --git a/file/tests/dd/mod.rs b/file/tests/dd/mod.rs index ff801e0c0..b88fbbd23 100644 --- a/file/tests/dd/mod.rs +++ b/file/tests/dd/mod.rs @@ -2,7 +2,7 @@ use std::fs::File; use std::io::Read; use std::path::PathBuf; -use plib::testing::{run_test_u8, TestPlanU8}; +use plib::testing::{TestPlanU8, run_test_u8}; fn get_test_file_path(filename: &str) -> PathBuf { let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); diff --git a/file/tests/file/mod.rs b/file/tests/file/mod.rs index 5a9f7ba79..7a8612db9 100644 --- a/file/tests/file/mod.rs +++ b/file/tests/file/mod.rs @@ -9,7 +9,7 @@ use std::{env, path::PathBuf}; -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn file_test(args: &[&str], expected_output: &str, expected_error: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/file/tests/find/mod.rs b/file/tests/find/mod.rs index 6d4138603..23ce6db31 100644 --- a/file/tests/find/mod.rs +++ b/file/tests/find/mod.rs @@ -1,7 +1,7 @@ -use std::fs::{remove_file, File}; +use std::fs::{File, remove_file}; use std::io::Write; -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn run_test_find( args: &[&str], diff --git a/file/tests/od/mod.rs b/file/tests/od/mod.rs index cdfdf6899..b83cd99ef 100644 --- a/file/tests/od/mod.rs +++ b/file/tests/od/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn od_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/fs/df.rs b/fs/df.rs index 76e14246f..2f2e3db84 100644 --- a/fs/df.rs +++ b/fs/df.rs @@ -14,7 +14,7 @@ mod mntent; use crate::mntent::MountTable; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[cfg(target_os = "macos")] use std::ffi::CStr; use std::{cmp, ffi::CString, fmt::Display, io}; diff --git a/ftw/src/dir.rs b/ftw/src/dir.rs index 991b1b462..e737518bd 100644 --- a/ftw/src/dir.rs +++ b/ftw/src/dir.rs @@ -1,4 +1,4 @@ -use crate::{open_long_filename, Error, ErrorKind, FileDescriptor}; +use crate::{Error, ErrorKind, FileDescriptor, open_long_filename}; use std::{ cell::{RefCell, RefMut}, collections::HashSet, diff --git a/ftw/tests/integration2.rs b/ftw/tests/integration2.rs index 465437327..6c88ae201 100644 --- a/ftw/tests/integration2.rs +++ b/ftw/tests/integration2.rs @@ -1,4 +1,4 @@ -use rand::{distributions::Standard, rngs::StdRng, Rng, SeedableRng}; +use rand::{Rng, SeedableRng, distributions::Standard, rngs::StdRng}; use std::{ffi::CString, fs, io, os::fd::AsRawFd, path::Path, path::PathBuf, sync::Mutex}; static GLOBAL_MUTEX: Mutex<()> = Mutex::new(()); diff --git a/gettext-rs/src/lib.rs b/gettext-rs/src/lib.rs index 996de8432..5f5ed54df 100644 --- a/gettext-rs/src/lib.rs +++ b/gettext-rs/src/lib.rs @@ -34,10 +34,10 @@ pub fn gettext>(msgid: T) -> String { #[macro_export] macro_rules! gettext { - ($fmt:expr) => { + ($fmt:expr_2021) => { format!($fmt) }; - ($fmt:expr, $($arg:tt)*) => { + ($fmt:expr_2021, $($arg:tt)*) => { format!($fmt, $($arg)*) }; } diff --git a/i18n/gencat.rs b/i18n/gencat.rs index a796cf56b..a7c0e8c25 100644 --- a/i18n/gencat.rs +++ b/i18n/gencat.rs @@ -1,6 +1,6 @@ use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian, WriteBytesExt}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::io::input_stream; use std::{ cell::RefCell, diff --git a/i18n/iconv.rs b/i18n/iconv.rs index b1e3c3c10..eb17fa207 100644 --- a/i18n/iconv.rs +++ b/i18n/iconv.rs @@ -8,12 +8,11 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use iconv_lib::{ - ascii, + ascii, utf_8, utf_16::{self, UTF16Variant}, utf_32::{self, UTF32Variant}, - utf_8, }; use plib::io::input_stream; use std::{ diff --git a/i18n/iconv_lib/utf_32.rs b/i18n/iconv_lib/utf_32.rs index f1dec4c95..df99521e3 100644 --- a/i18n/iconv_lib/utf_32.rs +++ b/i18n/iconv_lib/utf_32.rs @@ -114,29 +114,31 @@ pub fn from_ucs4 + 'static>( let mut buf = [0u8; 4]; let mut idx = 4; - let iter = iter::from_fn(move || loop { - if idx < 4 { - let byte = buf[idx]; - idx += 1; - return Some(byte); - } + let iter = iter::from_fn(move || { + loop { + if idx < 4 { + let byte = buf[idx]; + idx += 1; + return Some(byte); + } - match code_point.next() { - Some(cp) => { - if cp > 0x10FFFF { - if omit_invalid { - continue; - } else { - if !suppress_error { - eprintln!("Error: Invalid Unicode code point U+{:X}", cp); + match code_point.next() { + Some(cp) => { + if cp > 0x10FFFF { + if omit_invalid { + continue; + } else { + if !suppress_error { + eprintln!("Error: Invalid Unicode code point U+{:X}", cp); + } + exit(1); } - exit(1); } + write_u32(&mut buf, cp, variant); // Write code point to buffer + idx = 0; } - write_u32(&mut buf, cp, variant); // Write code point to buffer - idx = 0; + None => return None, } - None => return None, } }); diff --git a/i18n/iconv_lib/utf_8.rs b/i18n/iconv_lib/utf_8.rs index 17e1543e2..e9ed4ebf3 100644 --- a/i18n/iconv_lib/utf_8.rs +++ b/i18n/iconv_lib/utf_8.rs @@ -206,11 +206,7 @@ pub fn from_ucs4 + 'static>( code_point ); } - if omit_invalid { - None - } else { - Some(vec![]) - } + if omit_invalid { None } else { Some(vec![]) } } else { Some(vec![ 0xE0 | ((code_point >> 12) as u8), diff --git a/i18n/tests/gencat/mod.rs b/i18n/tests/gencat/mod.rs index 5c4fbf0ae..1d44f5b29 100644 --- a/i18n/tests/gencat/mod.rs +++ b/i18n/tests/gencat/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test_u8, TestPlanU8}; +use plib::testing::{TestPlanU8, run_test_u8}; use std::env; use std::path::PathBuf; use std::{fs::File, io::Read}; diff --git a/i18n/tests/iconv/mod.rs b/i18n/tests/iconv/mod.rs index 47b63ca70..b0d310a68 100644 --- a/i18n/tests/iconv/mod.rs +++ b/i18n/tests/iconv/mod.rs @@ -8,7 +8,7 @@ // #![allow(non_snake_case)] -use plib::testing::{run_test_u8, TestPlanU8}; +use plib::testing::{TestPlanU8, run_test_u8}; use std::env; use std::path::PathBuf; use std::{fs::File, io::Read}; diff --git a/m4/src/macros/builtin.rs b/m4/src/macros/builtin.rs index 22b492843..f23a0b3e3 100644 --- a/m4/src/macros/builtin.rs +++ b/m4/src/macros/builtin.rs @@ -6,17 +6,17 @@ use std::{io::Write, rc::Rc}; use super::eval::parse_integer; use super::{MacroDefinitionImplementation, MacroImplementation}; -use nom::error::{ContextError, FromExternalError}; use nom::IResult; +use nom::error::{ContextError, FromExternalError}; +use crate::EOF; use crate::error::{Result, ResultExt}; use crate::input::{Input, InputRead}; -use crate::lexer::{MacroName, MacroParseConfig, DEFAULT_QUOTE_CLOSE_TAG, DEFAULT_QUOTE_OPEN_TAG}; -use crate::macros::user_defined::UserDefinedMacro; +use crate::lexer::{DEFAULT_QUOTE_CLOSE_TAG, DEFAULT_QUOTE_OPEN_TAG, MacroName, MacroParseConfig}; use crate::macros::MacroDefinition; +use crate::macros::user_defined::UserDefinedMacro; use crate::output::DivertBufferNumber; use crate::state::{StackFrame, State}; -use crate::EOF; const AT_LEAST_ONE_MACRO_DEFINITION_EXPECT: &str = "There should always be at least one macro definition"; @@ -55,14 +55,15 @@ impl DefineMacro { ) -> Result<(State, Option)> { let mut args = frame.args.into_iter(); let name = if let Some(name_bytes) = args.next() { - if let Ok(name) = MacroName::try_from_slice(&name_bytes) { - name - } else { - log::warn!( - "Invalid macro name {:?}, skipping definition", - String::from_utf8_lossy(&name_bytes) - ); - return Ok((state, None)); + match MacroName::try_from_slice(&name_bytes) { + Ok(name) => name, + _ => { + log::warn!( + "Invalid macro name {:?}, skipping definition", + String::from_utf8_lossy(&name_bytes) + ); + return Ok((state, None)); + } } } else { log::warn!("No macro name specified, skipping definition"); diff --git a/m4/src/macros/eval.rs b/m4/src/macros/eval.rs index 4368361fb..c980de318 100644 --- a/m4/src/macros/eval.rs +++ b/m4/src/macros/eval.rs @@ -1,19 +1,19 @@ use std::io::Write; use nom::{ + IResult, branch::alt, bytes::complete::{tag, take_while}, combinator::fail, error::FromExternalError, sequence::{delimited, tuple}, - IResult, }; use crate::{ + Result, lexer::is_whitespace, - precedence::{self, binary_op, unary_op, Assoc, Operation}, + precedence::{self, Assoc, Operation, binary_op, unary_op}, state::{StackFrame, State}, - Result, }; use super::MacroImplementation; diff --git a/m4/src/macros/mod.rs b/m4/src/macros/mod.rs index 683f5da03..3c63827e3 100644 --- a/m4/src/macros/mod.rs +++ b/m4/src/macros/mod.rs @@ -11,9 +11,9 @@ use trace::{TraceoffMacro, TraceonMacro}; use user_defined::UserDefinedMacro; use crate::{ + Result, lexer::{MacroName, MacroParseConfig}, state::{StackFrame, State}, - Result, }; macro_rules! macro_enums { diff --git a/m4/src/macros/trace.rs b/m4/src/macros/trace.rs index 0cad52461..a4e960cf3 100644 --- a/m4/src/macros/trace.rs +++ b/m4/src/macros/trace.rs @@ -1,9 +1,9 @@ use std::io::Write; use crate::{ + Result, lexer::MacroName, state::{StackFrame, State}, - Result, }; use super::MacroImplementation; diff --git a/m4/src/macros/user_defined.rs b/m4/src/macros/user_defined.rs index efe702833..9d006898e 100644 --- a/m4/src/macros/user_defined.rs +++ b/m4/src/macros/user_defined.rs @@ -1,8 +1,8 @@ use std::io::Write; use crate::{ - state::{StackFrame, State}, Result, + state::{StackFrame, State}, }; use super::MacroImplementation; diff --git a/m4/src/main.rs b/m4/src/main.rs index 71dd4e54e..138770ec7 100644 --- a/m4/src/main.rs +++ b/m4/src/main.rs @@ -8,12 +8,11 @@ fn main() -> ExitCode { let stdout = std::io::stdout(); let mut stderr = std::io::stderr(); - if let Err(error) = posixutils_m4::run(stdout, &mut stderr, args) { - ExitCode::from(u8::try_from(error.get_exit_code()).unwrap_or_else(|e| { + match posixutils_m4::run(stdout, &mut stderr, args) { + Err(error) => ExitCode::from(u8::try_from(error.get_exit_code()).unwrap_or_else(|e| { eprintln!("Error casting exit code {e} into platform agnostic u8"); 1 - })) - } else { - ExitCode::SUCCESS + })), + _ => ExitCode::SUCCESS, } } diff --git a/m4/src/main_loop.rs b/m4/src/main_loop.rs index 3a1197324..2cae58ee6 100644 --- a/m4/src/main_loop.rs +++ b/m4/src/main_loop.rs @@ -1,10 +1,10 @@ use std::io::Write; +use crate::EOF; use crate::error::{Error, ErrorKind}; use crate::lexer::{is_alpha, is_space}; use crate::macros::MacroImplementation; use crate::state::{StackFrame, State}; -use crate::EOF; /// The main loop, the most important function in this program. pub(crate) fn main_loop(mut state: State, stderr: &mut dyn Write) -> crate::error::Result { diff --git a/m4/src/precedence.rs b/m4/src/precedence.rs index 9e1e03e74..9a0b478fd 100644 --- a/m4/src/precedence.rs +++ b/m4/src/precedence.rs @@ -224,7 +224,7 @@ where return Err(Err::Error(E::from_error_kind( i1, ErrorKind::Tag, - ))) + ))); } }, }; @@ -234,7 +234,7 @@ where i, ErrorKind::Tag, e, - ))) + ))); } Ok(r) => r, }; @@ -266,7 +266,7 @@ where Operator::Binary(op, _, _) => match operands.pop() { Some(lhs) => Operation::Binary(lhs, op, value), None => { - return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Tag))) + return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Tag))); } }, }; @@ -276,7 +276,7 @@ where i, ErrorKind::Tag, e, - ))) + ))); } Ok(r) => r, }; diff --git a/m4/src/state.rs b/m4/src/state.rs index 39450e5b0..18cf3ab80 100644 --- a/m4/src/state.rs +++ b/m4/src/state.rs @@ -1,11 +1,11 @@ use std::{cell::RefCell, collections::HashMap, io::Write, process::ExitStatus, rc::Rc}; use crate::{ + EOF, input::{Input, InputState, InputStateRef}, - lexer::{is_alphnumeric, MacroName, ParseConfig}, - macros::{trace::Trace, BuiltinMacro, MacroDefinition}, + lexer::{MacroName, ParseConfig, is_alphnumeric}, + macros::{BuiltinMacro, MacroDefinition, trace::Trace}, output::{Output, OutputState}, - EOF, }; pub struct State { diff --git a/make/src/parser/parse.rs b/make/src/parser/parse.rs index e9335216d..a76a20502 100644 --- a/make/src/parser/parse.rs +++ b/make/src/parser/parse.rs @@ -399,7 +399,7 @@ impl Makefile { Ok(parsed.root()) } - pub fn rules(&self) -> impl Iterator { + pub fn rules(&self) -> impl Iterator + use<> { self.syntax().children().filter_map(Rule::cast) } @@ -408,7 +408,7 @@ impl Makefile { .filter(move |rule| rule.targets().any(|t| t == target)) } - pub fn variable_definitions(&self) -> impl Iterator { + pub fn variable_definitions(&self) -> impl Iterator + use<> { self.syntax() .children() .filter_map(VariableDefinition::cast) @@ -431,14 +431,14 @@ impl Makefile { } impl Rule { - pub fn targets(&self) -> impl Iterator { + pub fn targets(&self) -> impl Iterator + use<> { self.syntax() .children_with_tokens() .take_while(|it| it.as_token().map_or(true, |t| t.kind() != COLON)) .filter_map(|it| it.as_token().map(|t| t.text().to_string())) } - pub fn prerequisites(&self) -> impl Iterator { + pub fn prerequisites(&self) -> impl Iterator + use<> { self.syntax() .children() .find(|it| it.kind() == EXPR) @@ -456,7 +456,7 @@ impl Rule { }) } - pub fn recipes(&self) -> impl Iterator { + pub fn recipes(&self) -> impl Iterator + use<> { self.syntax() .children() .filter(|it| it.kind() == RECIPE) diff --git a/make/tests/integration.rs b/make/tests/integration.rs index 9a583df0c..7b6c0a442 100644 --- a/make/tests/integration.rs +++ b/make/tests/integration.rs @@ -360,11 +360,13 @@ mod macros { ); fn set_env_vars() { - env::set_var("MACRO", "echo"); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::set_var("MACRO", "echo") }; } fn clean_env_vars() { - env::remove_var("MACRO"); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::remove_var("MACRO") }; } } } diff --git a/misc/test.rs b/misc/test.rs index 98654ce34..2da0fcc0d 100644 --- a/misc/test.rs +++ b/misc/test.rs @@ -14,7 +14,7 @@ use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; use std::path::Path; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; /// Unary operators #[allow(clippy::upper_case_acronyms)] diff --git a/misc/tests/false/mod.rs b/misc/tests/false/mod.rs index 694ded2f3..759d3d320 100644 --- a/misc/tests/false/mod.rs +++ b/misc/tests/false/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn truefalse_test(cmd: &str, expected_exit_code: i32) { run_test(TestPlan { diff --git a/misc/tests/test/mod.rs b/misc/tests/test/mod.rs index 3006e1d28..689762e37 100644 --- a/misc/tests/test/mod.rs +++ b/misc/tests/test/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn test_test(args: &[&str], expected_code: i32) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/misc/tests/true/mod.rs b/misc/tests/true/mod.rs index 9d6972bb1..309701d46 100644 --- a/misc/tests/true/mod.rs +++ b/misc/tests/true/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn truefalse_test(cmd: &str, expected_exit_code: i32) { run_test(TestPlan { diff --git a/pathnames/basename.rs b/pathnames/basename.rs index 75a5fb467..ff423ddcd 100644 --- a/pathnames/basename.rs +++ b/pathnames/basename.rs @@ -10,7 +10,7 @@ use std::path::Path; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command( diff --git a/pathnames/dirname.rs b/pathnames/dirname.rs index 4ef2277c1..6ae02d9b5 100644 --- a/pathnames/dirname.rs +++ b/pathnames/dirname.rs @@ -11,7 +11,7 @@ use std::ffi::OsString; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command( diff --git a/pathnames/pathchk.rs b/pathnames/pathchk.rs index 0fb6bdb75..169fd63dd 100644 --- a/pathnames/pathchk.rs +++ b/pathnames/pathchk.rs @@ -11,7 +11,7 @@ use std::ffi::CString; use std::path::{Component, Path}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; const _POSIX_PATH_MAX: usize = 255; const _POSIX_NAME_MAX: usize = 14; diff --git a/pathnames/realpath.rs b/pathnames/realpath.rs index 81e823cad..76dbb4e29 100644 --- a/pathnames/realpath.rs +++ b/pathnames/realpath.rs @@ -10,7 +10,7 @@ use std::path::{Component, Path, PathBuf}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; /// realpath -- return resolved canonical path #[derive(Parser)] diff --git a/pathnames/tests/basename/mod.rs b/pathnames/tests/basename/mod.rs index 6425fd03b..452778d82 100644 --- a/pathnames/tests/basename/mod.rs +++ b/pathnames/tests/basename/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; #[test] fn basename_basic() { diff --git a/pathnames/tests/dirname/mod.rs b/pathnames/tests/dirname/mod.rs index 1722e0af0..d86181d18 100644 --- a/pathnames/tests/dirname/mod.rs +++ b/pathnames/tests/dirname/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; #[test] fn dirname_basic() { diff --git a/pathnames/tests/realpath/mod.rs b/pathnames/tests/realpath/mod.rs index db215c40a..dce71b272 100644 --- a/pathnames/tests/realpath/mod.rs +++ b/pathnames/tests/realpath/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn realpath_test(args: &[&str], stdout: &str, stderr: &str, expected_code: i32) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/plib/src/sccsfile.rs b/plib/src/sccsfile.rs index d5c916b2b..2ac5a8fc6 100644 --- a/plib/src/sccsfile.rs +++ b/plib/src/sccsfile.rs @@ -313,7 +313,10 @@ E 2 match &sccs_file.edits[0] { SccsEdit::Insert(line) => { - assert_eq!(line, "I 1\napple\nbanana\ncharlie\ndelta\necho\nfoxtrot\ngolf\nhotel\nindia\njuliet\nkilo\nlima\nmike\nE 1\n"); + assert_eq!( + line, + "I 1\napple\nbanana\ncharlie\ndelta\necho\nfoxtrot\ngolf\nhotel\nindia\njuliet\nkilo\nlima\nmike\nE 1\n" + ); } _ => panic!("Unexpected edit type"), } diff --git a/process/Cargo.toml b/process/Cargo.toml index db18ec6d5..1e163af80 100644 --- a/process/Cargo.toml +++ b/process/Cargo.toml @@ -17,7 +17,7 @@ dirs = "5.0" chrono-tz.workspace = true [build-dependencies] -bindgen = { version = "0.70.0", features = ["runtime"] } +bindgen = { version = "0.71", features = ["runtime"] } [lints] workspace = true diff --git a/process/batch.rs b/process/batch.rs index 4e440ae38..a12427d9e 100644 --- a/process/batch.rs +++ b/process/batch.rs @@ -8,7 +8,7 @@ // use chrono::{DateTime, Local, TimeZone, Utc}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use libc::{getlogin, getpwnam, passwd}; use std::{ @@ -229,7 +229,7 @@ impl Job { format!( "#!{shell}\n# atrun uid={user_uid} gid={user_gid}\n# mail {user_name} {}\numask 22\n{env}\ncd {} || {{\n\techo 'Execution directory inaccessible' >&2\n\texit 1 \n}}\n{cmd}", - if mail {1} else {0}, + if mail { 1 } else { 0 }, call_place.to_string_lossy() ) } diff --git a/process/env.rs b/process/env.rs index 3884ed5b9..f619c2f93 100644 --- a/process/env.rs +++ b/process/env.rs @@ -14,7 +14,7 @@ use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command(version, about = gettext("env - set the environment for command invocation"))] diff --git a/process/fuser.rs b/process/fuser.rs index fffdb7e83..621a148ae 100644 --- a/process/fuser.rs +++ b/process/fuser.rs @@ -9,7 +9,7 @@ use std::collections::BTreeMap; use std::ffi::CStr; -use std::fs::{metadata, Metadata}; +use std::fs::{Metadata, metadata}; use std::io::{self, Write}; use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; @@ -18,7 +18,7 @@ use std::thread; use std::time::Duration; use clap::{CommandFactory, Parser}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; const NAME_FIELD: usize = 20; @@ -1220,7 +1220,7 @@ mod linux { mod macos { use super::*; - #[allow(warnings, missing_docs)] + #[allow(warnings, missing_docs, unsafe_op_in_unsafe_fn)] pub mod osx_libproc_bindings { include!(concat!(env!("OUT_DIR"), "/osx_libproc_bindings.rs")); } diff --git a/process/kill.rs b/process/kill.rs index ec897894a..7c9d19d0e 100644 --- a/process/kill.rs +++ b/process/kill.rs @@ -9,7 +9,7 @@ mod signal; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use crate::signal::{list_signals, lookup_signum}; diff --git a/process/nice.rs b/process/nice.rs index 4804bf402..1e4abd660 100644 --- a/process/nice.rs +++ b/process/nice.rs @@ -12,7 +12,7 @@ use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command( diff --git a/process/nohup.rs b/process/nohup.rs index bec304c5f..b9e0311b2 100644 --- a/process/nohup.rs +++ b/process/nohup.rs @@ -13,8 +13,8 @@ use std::io::{self, IsTerminal}; use std::os::unix::io::AsRawFd; use std::process::{self, Command}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use libc::{dup, dup2, signal, SIGHUP, SIG_IGN}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; +use libc::{SIG_IGN, SIGHUP, dup, dup2, signal}; enum NohupDir { Current, diff --git a/process/renice.rs b/process/renice.rs index 91be72790..2d645981c 100644 --- a/process/renice.rs +++ b/process/renice.rs @@ -10,7 +10,7 @@ use std::ffi::CString; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use libc::{getpwnam, passwd}; use plib::priority::{getpriority, setpriority}; diff --git a/process/tests/fuser/mod.rs b/process/tests/fuser/mod.rs index 85b6d82a2..467118f33 100644 --- a/process/tests/fuser/mod.rs +++ b/process/tests/fuser/mod.rs @@ -1,4 +1,4 @@ -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; use std::process::Output; mod basic; diff --git a/process/tests/xargs/mod.rs b/process/tests/xargs/mod.rs index 15ad9221e..05f3657f0 100644 --- a/process/tests/xargs/mod.rs +++ b/process/tests/xargs/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn xargs_test(test_data: &str, expected_output: &str, args: Vec<&str>) { run_test(TestPlan { diff --git a/process/timeout.rs b/process/timeout.rs index 8faa211af..5a442fd0e 100644 --- a/process/timeout.rs +++ b/process/timeout.rs @@ -14,12 +14,12 @@ use std::os::unix::fs::PermissionsExt; use std::os::unix::process::{CommandExt, ExitStatusExt}; use std::path::Path; use std::process::{Command, ExitStatus}; -use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use std::time::Duration; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use crate::signal::parse_signal; diff --git a/process/xargs.rs b/process/xargs.rs index 7b53e2785..a7c8152fc 100644 --- a/process/xargs.rs +++ b/process/xargs.rs @@ -18,7 +18,7 @@ use std::io::{self, Read}; use std::process::{Command, Stdio}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::BUFSZ; const ARG_MAX: i32 = 131072; // arbitrary. todo: discover actual value diff --git a/sccs/tests/what/mod.rs b/sccs/tests/what/mod.rs index ac07b259e..547a3acfa 100644 --- a/sccs/tests/what/mod.rs +++ b/sccs/tests/what/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::path::PathBuf; fn test_file_path(file_name: &str) -> PathBuf { diff --git a/sccs/what.rs b/sccs/what.rs index eef5f390a..245f07f91 100644 --- a/sccs/what.rs +++ b/sccs/what.rs @@ -12,7 +12,7 @@ use std::io::{self, BufRead, BufReader}; use std::path::{Path, PathBuf}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[derive(Parser)] #[command(version, about = gettext("what - identify SCCS files"))] @@ -59,11 +59,14 @@ fn main() -> io::Result<()> { for file in &args.files { let path = Path::new(file); - if let Ok(file) = File::open(path) { - let reader = BufReader::new(file); - process_file(reader, args.single)?; - } else { - eprintln!("what: {}: {}", gettext("Cannot open file"), file.display()); + match File::open(path) { + Ok(file) => { + let reader = BufReader::new(file); + process_file(reader, args.single)?; + } + _ => { + eprintln!("what: {}: {}", gettext("Cannot open file"), file.display()); + } } } diff --git a/screen/stty.rs b/screen/stty.rs index 362f88c8c..f7fb57c0e 100644 --- a/screen/stty.rs +++ b/screen/stty.rs @@ -16,11 +16,11 @@ use std::collections::HashMap; use std::io::{self, Error, ErrorKind}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; -use osdata::{ParamType, PARG, PNEG}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; +use osdata::{PARG, PNEG, ParamType}; use termios::{ - cc_t, cfgetispeed, cfgetospeed, cfsetispeed, cfsetospeed, speed_t, tcflag_t, tcsetattr, - Termios, TCSANOW, + TCSANOW, Termios, cc_t, cfgetispeed, cfgetospeed, cfsetispeed, cfsetospeed, speed_t, tcflag_t, + tcsetattr, }; const HDR_SAVE: &str = "pfmt1"; diff --git a/screen/tabs.rs b/screen/tabs.rs index 86746169e..97e218138 100644 --- a/screen/tabs.rs +++ b/screen/tabs.rs @@ -15,8 +15,8 @@ use std::io::{self, Error, ErrorKind, Write}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; -use terminfo::{capability as cap, Database}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; +use terminfo::{Database, capability as cap}; // arbitrarily chosen. todo: search if POSIX-ly correct. const MAX_STOPS: usize = 100; diff --git a/screen/tput.rs b/screen/tput.rs index 11160d973..0421f3745 100644 --- a/screen/tput.rs +++ b/screen/tput.rs @@ -14,8 +14,8 @@ use std::io; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; -use terminfo::{capability as cap, Database}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; +use terminfo::{Database, capability as cap}; #[derive(Parser)] #[command(version, about = gettext("tput - change terminal characteristics"))] diff --git a/sh/os/signals.rs b/sh/os/signals.rs index daf505e3b..f58c6a3aa 100644 --- a/sh/os/signals.rs +++ b/sh/os/signals.rs @@ -233,16 +233,18 @@ extern "C" fn write_signal_to_buffer(signal: libc::c_int) { /// # Safety /// cannot be called by multiple threads pub unsafe fn setup_signal_handling() { - let (read_pipe, write_pipe) = pipe().expect("could not create signal buffer pipe"); - let result = unsafe { libc::fcntl(read_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; - if result < 0 { - panic!( - "failed initialize async buffer for signal handling ({})", - get_current_errno_value() - ); + unsafe { + let (read_pipe, write_pipe) = pipe().expect("could not create signal buffer pipe"); + let result = libc::fcntl(read_pipe.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK); + if result < 0 { + panic!( + "failed initialize async buffer for signal handling ({})", + get_current_errno_value() + ); + } + SIGNAL_WRITE = Some(write_pipe.into_raw_fd()); + SIGNAL_READ = Some(read_pipe.into_raw_fd()); } - SIGNAL_WRITE = Some(write_pipe.into_raw_fd()); - SIGNAL_READ = Some(read_pipe.into_raw_fd()); } fn get_pending_signal() -> Option { @@ -270,33 +272,41 @@ fn get_pending_signal() -> Option { } unsafe fn handle_signal(signal: Signal, handler: libc::sighandler_t) { - // sigaction contains different field on different systems, we can't - // initialize it directly - let mut action = std::mem::zeroed::(); - action.sa_sigaction = handler; - // never fails - libc::sigemptyset(&mut action.sa_mask); - action.sa_flags = libc::SA_SIGINFO; + unsafe { + // sigaction contains different field on different systems, we can't + // initialize it directly + let mut action = std::mem::zeroed::(); + action.sa_sigaction = handler; + // never fails + libc::sigemptyset(&mut action.sa_mask); + action.sa_flags = libc::SA_SIGINFO; - let result = libc::sigaction(signal.into(), &action, std::ptr::null_mut()); - if result < 0 { - panic!("failed to set signal handler") + let result = libc::sigaction(signal.into(), &action, std::ptr::null_mut()); + if result < 0 { + panic!("failed to set signal handler") + } } } pub unsafe fn handle_signal_ignore(signal: Signal) { - handle_signal(signal, libc::SIG_IGN); + unsafe { + handle_signal(signal, libc::SIG_IGN); + } } pub unsafe fn handle_signal_default(signal: Signal) { - handle_signal(signal, libc::SIG_DFL); + unsafe { + handle_signal(signal, libc::SIG_DFL); + } } pub unsafe fn handle_signal_write_to_signal_buffer(signal: Signal) { - handle_signal( - signal, - write_signal_to_buffer as *const extern "C" fn(libc::c_int) as libc::sighandler_t, - ) + unsafe { + handle_signal( + signal, + write_signal_to_buffer as *const extern "C" fn(libc::c_int) as libc::sighandler_t, + ) + } } #[derive(Clone)] diff --git a/sh/tests/integration.rs b/sh/tests/integration.rs index 046b53278..24b75d623 100644 --- a/sh/tests/integration.rs +++ b/sh/tests/integration.rs @@ -17,13 +17,15 @@ fn set_env_vars() { } else { current_dir.join("sh/tests/read_dir") }; - std::env::set_var("TEST_READ_DIR", read_dir); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::set_var("TEST_READ_DIR", read_dir) }; let write_dir = Path::new(concat!(env!("CARGO_TARGET_TMPDIR"), "/sh_test_write_dir")); if !write_dir.exists() { std::fs::create_dir(&write_dir).expect("failed to create write_dir"); } - std::env::set_var("TEST_WRITE_DIR", write_dir); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::set_var("TEST_WRITE_DIR", write_dir) }; TEST_VARS_ARE_SET.store(true, Ordering::SeqCst); } while !TEST_VARS_ARE_SET.load(Ordering::SeqCst) {} diff --git a/sh/wordexp/pathname.rs b/sh/wordexp/pathname.rs index 4eb9d819f..448ba2e31 100644 --- a/sh/wordexp/pathname.rs +++ b/sh/wordexp/pathname.rs @@ -32,10 +32,11 @@ struct DefaultFileSystem; impl FileSystem for DefaultFileSystem { fn read_dir(&self, path: &Path) -> DirContent { let mut result = vec![DirEntry::Dir(".".into()), DirEntry::Dir("..".into())]; - let dir_iter = if let Ok(iter) = std::fs::read_dir(path) { - iter - } else { - return result; + let dir_iter = match std::fs::read_dir(path) { + Ok(iter) => iter, + _ => { + return result; + } }; for entry in dir_iter { let entry = if let Ok(item) = entry { item } else { continue }; diff --git a/sys/getconf.rs b/sys/getconf.rs index 09edde7b0..25d7a9db8 100644 --- a/sys/getconf.rs +++ b/sys/getconf.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::ffi::CString; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use libc::{pathconf, sysconf}; #[derive(Parser)] diff --git a/sys/ipcrm.rs b/sys/ipcrm.rs index 6b8f57847..fa7c922fd 100644 --- a/sys/ipcrm.rs +++ b/sys/ipcrm.rs @@ -12,7 +12,7 @@ use std::io::{self, Error, ErrorKind}; use std::ptr; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; #[cfg(not(target_os = "macos"))] use libc::{msgctl, msgget, msqid_ds}; use libc::{semctl, semget, shmctl, shmget, shmid_ds}; diff --git a/sys/ipcs.rs b/sys/ipcs.rs index e4fa40445..3c28776d1 100644 --- a/sys/ipcs.rs +++ b/sys/ipcs.rs @@ -9,7 +9,7 @@ use chrono::Local; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; /// ipcs - report XSI interprocess communication facilities status #[derive(Parser)] @@ -75,7 +75,7 @@ fn display_message_queues(_args: &Args) { #[cfg(not(target_os = "macos"))] { - use libc::{msgctl, msqid_ds, IPC_STAT}; + use libc::{IPC_STAT, msgctl, msqid_ds}; let mut msqid: i32 = 0; let mut msg_ds: msqid_ds = unsafe { std::mem::zeroed() }; @@ -124,7 +124,7 @@ fn display_message_queues(_args: &Args) { } fn display_shared_memory(_args: &Args) { - use libc::{shmctl, shmid_ds, IPC_STAT}; + use libc::{IPC_STAT, shmctl, shmid_ds}; use std::ffi::CStr; #[cfg(target_os = "macos")] @@ -183,7 +183,7 @@ fn display_shared_memory(_args: &Args) { } fn display_semaphores(_args: &Args) { - use libc::{semctl, semid_ds, IPC_STAT}; + use libc::{IPC_STAT, semctl, semid_ds}; use std::ffi::CStr; let mut semid: i32 = 0; diff --git a/sys/ps.rs b/sys/ps.rs index 59a212912..630cd41be 100644 --- a/sys/ps.rs +++ b/sys/ps.rs @@ -16,7 +16,7 @@ mod pslinux; use std::collections::HashMap; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; #[cfg(target_os = "macos")] mod platform { diff --git a/sys/tests/getconf/mod.rs b/sys/tests/getconf/mod.rs index 91564bf9c..8de067ab7 100644 --- a/sys/tests/getconf/mod.rs +++ b/sys/tests/getconf/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; use std::process::Output; fn run_getconf_test(args: Vec<&str>, expected_exit_code: i32, check_fn: fn(&TestPlan, &Output)) { diff --git a/sys/uname.rs b/sys/uname.rs index 35ed6f261..1926dcaae 100644 --- a/sys/uname.rs +++ b/sys/uname.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; /// uname - return system name #[derive(Parser)] diff --git a/sys/who.rs b/sys/who.rs index ccfd4544d..c85d016b4 100644 --- a/sys/who.rs +++ b/sys/who.rs @@ -14,7 +14,7 @@ use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::utmpx::Utmpx; use plib::{curuser, platform, utmpx}; diff --git a/text/asa.rs b/text/asa.rs index 1f76ad7a5..1a5ac908f 100644 --- a/text/asa.rs +++ b/text/asa.rs @@ -15,7 +15,7 @@ use std::io::{self, BufRead}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::io::input_reader; /// asa - interpret carriage-control characters diff --git a/text/comm.rs b/text/comm.rs index 81a45cc1e..1b5b5e37d 100644 --- a/text/comm.rs +++ b/text/comm.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::fs; use std::io::{self, BufRead, Write}; use std::path::PathBuf; @@ -50,13 +50,7 @@ fn line_out(lead_dup: &'static str, outmask: u32, curtype: u32, s: &str) -> io:: io::stdout().write_all(s.as_bytes())?; } NO2 => { - let lead_f2 = { - if (outmask & NO1) != 0 { - "" - } else { - "\t" - } - }; + let lead_f2 = { if (outmask & NO1) != 0 { "" } else { "\t" } }; let newstr = format!("{}{}", lead_f2, s); io::stdout().write_all(newstr.as_bytes())?; } diff --git a/text/csplit.rs b/text/csplit.rs index c4e12b377..d348ac7ad 100644 --- a/text/csplit.rs +++ b/text/csplit.rs @@ -11,7 +11,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use regex::Regex; use std::fs::{self, File, OpenOptions}; use std::io::{self, BufRead, Error, ErrorKind, Read, Write}; @@ -1163,8 +1163,9 @@ mod tests { let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); - let expected = - String::from(" printf(\"This is function 2\\n\");\n}\n\nvoid func3() {\n printf(\"This is function 3\\n\");\n}\n"); + let expected = String::from( + " printf(\"This is function 2\\n\");\n}\n\nvoid func3() {\n printf(\"This is function 3\\n\");\n}\n", + ); assert_eq!(contents, expected); diff --git a/text/cut.rs b/text/cut.rs index a54a95b41..5e1827432 100644 --- a/text/cut.rs +++ b/text/cut.rs @@ -10,7 +10,7 @@ use std::io::{self, BufRead, Error, ErrorKind, Read}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::path::PathBuf; /// Cut - cut out selected fields of each line of a file diff --git a/text/diff.rs b/text/diff.rs index c3fd8d984..6e700e59c 100644 --- a/text/diff.rs +++ b/text/diff.rs @@ -24,7 +24,7 @@ use diff_util::{ file_diff::FileDiff, functions::check_existance, }; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; /// diff - compare two files #[derive(Parser, Clone)] diff --git a/text/diff_util/file_diff.rs b/text/diff_util/file_diff.rs index 16f98e332..6aee79401 100755 --- a/text/diff_util/file_diff.rs +++ b/text/diff_util/file_diff.rs @@ -13,7 +13,7 @@ use std::{ cmp::Reverse, collections::HashMap, fmt::Write, - fs::{read_to_string, File}, + fs::{File, read_to_string}, io::{self, BufReader, Read}, os::unix::fs::MetadataExt, path::PathBuf, diff --git a/text/expand.rs b/text/expand.rs index 022ff299c..270df8543 100644 --- a/text/expand.rs +++ b/text/expand.rs @@ -11,9 +11,9 @@ use std::io::{self, BufWriter, Read, Write}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; /// expand - convert tabs to spaces #[derive(Parser)] diff --git a/text/fold.rs b/text/fold.rs index db9f025f4..e61e7ad0e 100644 --- a/text/fold.rs +++ b/text/fold.rs @@ -11,9 +11,9 @@ use std::io::{self, Read, Write}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; const TABSTOP: usize = 8; diff --git a/text/grep.rs b/text/grep.rs index 5ee38227d..767f27548 100644 --- a/text/grep.rs +++ b/text/grep.rs @@ -8,8 +8,8 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use libc::{regcomp, regex_t, regexec, regfree, REG_EXTENDED, REG_ICASE, REG_NOMATCH}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; +use libc::{REG_EXTENDED, REG_ICASE, REG_NOMATCH, regcomp, regex_t, regexec, regfree}; use std::{ ffi::CString, fs::File, diff --git a/text/head.rs b/text/head.rs index e0bb129ed..c3c7b6654 100644 --- a/text/head.rs +++ b/text/head.rs @@ -12,9 +12,9 @@ use std::io::{self, Read, StdoutLock, Write}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; const N_C_GROUP: &str = "N_C_GROUP"; diff --git a/text/join.rs b/text/join.rs index 63e1a9ffc..da7f6de05 100644 --- a/text/join.rs +++ b/text/join.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; diff --git a/text/nl.rs b/text/nl.rs index bf45b7310..3e15c2192 100644 --- a/text/nl.rs +++ b/text/nl.rs @@ -8,7 +8,7 @@ // use clap::{Parser, ValueEnum}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use regex::Regex; use std::fs; use std::io::{self, BufRead, Read}; @@ -110,10 +110,9 @@ impl FromStr for LineNumberingStyle { "n" => Ok(LineNumberingStyle::None), s => { if let Some(re) = s.strip_prefix('p') { - if let Ok(regexp) = Regex::new(re) { - Ok(LineNumberingStyle::Regex(regexp)) - } else { - Err(format!("invalid regular expression: {re}")) + match Regex::new(re) { + Ok(regexp) => Ok(LineNumberingStyle::Regex(regexp)), + _ => Err(format!("invalid regular expression: {re}")), } } else { Err(format!("invalid variant: {s}")) diff --git a/text/paste.rs b/text/paste.rs index e63564ef8..974774717 100644 --- a/text/paste.rs +++ b/text/paste.rs @@ -11,7 +11,7 @@ // - improve: don't open all files at once in --serial mode use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::cell::{OnceCell, RefCell}; use std::error::Error; use std::fs::File; @@ -142,7 +142,7 @@ impl<'a> DelimiterState<'a> { match self { DelimiterState::MultipleDelimiters { delimiters, - ref mut delimiters_iterator, + delimiters_iterator, .. } => { *delimiters_iterator = delimiters.iter().cycle(); diff --git a/text/pr.rs b/text/pr.rs index 309a4a478..0389c6c60 100644 --- a/text/pr.rs +++ b/text/pr.rs @@ -16,10 +16,10 @@ use std::path::PathBuf; use std::process::ExitCode; use chrono::{DateTime, Local}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::io::input_stream; -use self::pr_util::{line_transform, Args, PageIterator, Parameters}; +use self::pr_util::{Args, PageIterator, Parameters, line_transform}; const FORM_FEED: char = 12 as char; const TAB: char = '\t'; diff --git a/text/pr_util/args.rs b/text/pr_util/args.rs index 2544dab43..428c35c47 100644 --- a/text/pr_util/args.rs +++ b/text/pr_util/args.rs @@ -258,7 +258,7 @@ fn parse_separator(s: &str) -> Result { } macro_rules! impl_char_and_number { - ($t:tt, $option:expr, $default_chr:expr, $default_num:expr) => { + ($t:tt, $option:expr_2021, $default_chr:expr_2021, $default_num:expr_2021) => { #[derive(Clone)] pub struct $t { chr: char, @@ -297,7 +297,7 @@ macro_rules! impl_char_and_number { return Ok(Self { chr, ..Default::default() - }) + }); } Some((start, _)) => { if let Ok(num) = &s[start..].parse() { diff --git a/text/pr_util/line_iterator.rs b/text/pr_util/line_iterator.rs index f9ef45840..dfc9a0aff 100644 --- a/text/pr_util/line_iterator.rs +++ b/text/pr_util/line_iterator.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use crate::{Line, FORM_FEED}; +use crate::{FORM_FEED, Line}; use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read}; diff --git a/text/sed.rs b/text/sed.rs index 7c4376c98..eba1d81cd 100644 --- a/text/sed.rs +++ b/text/sed.rs @@ -7,11 +7,11 @@ // SPDX-License-Identifier: MIT // -use clap::{command, Parser}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use clap::{Parser, command}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use libc::{ - ioctl, regcomp, regex_t, regexec, regmatch_t, winsize, REG_EXTENDED, STDERR_FILENO, - STDIN_FILENO, STDOUT_FILENO, TIOCGWINSZ, + REG_EXTENDED, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO, TIOCGWINSZ, ioctl, regcomp, regex_t, + regexec, regmatch_t, winsize, }; use std::sync::Mutex; use std::{ @@ -222,7 +222,7 @@ impl AddressRange { return Err(SedError::ScriptParse( "address isn't empty, position or range".to_string(), None, - )) + )); } 2 => Some((false, false)), 0 => return Ok(None), @@ -2170,20 +2170,23 @@ impl Sed { } fn execute_r(&mut self, rfile: PathBuf) { - if let Ok(file) = File::open(rfile) { - let reader = BufReader::new(file); - for line in reader.lines() { - let Ok(line) = line else { - break; - }; - self.pattern_space += "\n"; - self.pattern_space += &line; + match File::open(rfile) { + Ok(file) => { + let reader = BufReader::new(file); + for line in reader.lines() { + let Ok(line) = line else { + break; + }; + self.pattern_space += "\n"; + self.pattern_space += &line; + } + if self.current_end.is_none() { + self.current_end = Some("\n".to_string()); + } } - if self.current_end.is_none() { + _ => { self.current_end = Some("\n".to_string()); } - } else { - self.current_end = Some("\n".to_string()); } } diff --git a/text/sort.rs b/text/sort.rs index c0012bf0b..78783582c 100644 --- a/text/sort.rs +++ b/text/sort.rs @@ -17,7 +17,7 @@ use std::{ }; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; /// Sort, merge, or sequence check text files #[derive(Parser)] @@ -310,11 +310,7 @@ fn numeric_sort_filter(input: &str) -> Option { } } - if found_number { - Some(result) - } else { - None - } + if found_number { Some(result) } else { None } } /// Compares two strings numerically, extracting numbers and performing a numeric comparison. diff --git a/text/tail.rs b/text/tail.rs index c179520fc..a00e5f9f8 100644 --- a/text/tail.rs +++ b/text/tail.rs @@ -11,7 +11,7 @@ use std::sync::mpsc; use std::time::Duration; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use notify_debouncer_full::new_debouncer; use notify_debouncer_full::notify::event::{ModifyKind, RemoveKind}; use notify_debouncer_full::notify::{EventKind, RecursiveMode, Watcher}; @@ -131,8 +131,8 @@ enum FileOrStdin { impl FileOrStdin { fn get_buf_read(&mut self) -> &mut dyn BufRead { match self { - Self::File(_, ref mut bu) => bu, - Self::Stdin(ref mut st) => st, + Self::File(_, bu) => bu, + Self::Stdin(st) => st, } } } diff --git a/text/tests/comm/mod.rs b/text/tests/comm/mod.rs index b32773824..c21faddc8 100644 --- a/text/tests/comm/mod.rs +++ b/text/tests/comm/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::fs; use std::path::PathBuf; diff --git a/text/tests/csplit/mod.rs b/text/tests/csplit/mod.rs index 6c557907c..4cdc2bf7c 100644 --- a/text/tests/csplit/mod.rs +++ b/text/tests/csplit/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn csplit_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tests/cut/mod.rs b/text/tests/cut/mod.rs index 7df519463..688d65394 100644 --- a/text/tests/cut/mod.rs +++ b/text/tests/cut/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn cut_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tests/diff-tests.rs b/text/tests/diff-tests.rs index 8f159c23b..e0e0038dd 100644 --- a/text/tests/diff-tests.rs +++ b/text/tests/diff-tests.rs @@ -12,7 +12,7 @@ mod constants; use constants::{EXIT_STATUS_DIFFERENCE, EXIT_STATUS_NO_DIFFERENCE}; -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{collections::HashMap, path::PathBuf, process::Stdio, sync::LazyLock}; fn diff_test(args: &[&str], expected_output: &str, expected_diff_exit_status: u8) { diff --git a/text/tests/expand/mod.rs b/text/tests/expand/mod.rs index e1c4e6b67..8670e4e37 100644 --- a/text/tests/expand/mod.rs +++ b/text/tests/expand/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn expand_test_noargs(test_data: &str, expected_output: &str) { run_test(TestPlan { diff --git a/text/tests/fold/mod.rs b/text/tests/fold/mod.rs index 537fd19a8..d94327821 100644 --- a/text/tests/fold/mod.rs +++ b/text/tests/fold/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::fs::File; use std::io::Read; use std::path::PathBuf; diff --git a/text/tests/grep/mod.rs b/text/tests/grep/mod.rs index 49ef06f6d..fd02fc632 100644 --- a/text/tests/grep/mod.rs +++ b/text/tests/grep/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; const LINES_INPUT: &str = "line_{1}\np_line_{2}_s\n line_{3} \nLINE_{4}\np_LINE_{5}_s\nl_{6}\nline_{70}\n"; @@ -253,7 +253,13 @@ fn test_basic_regexp_no_messages_without_error_02() { #[test] fn test_basic_regexp_no_messages_with_error_01() { - grep_test(&["-s", BRE, "-", BAD_INPUT_FILE], LINES_INPUT, "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", "", 2); + grep_test( + &["-s", BRE, "-", BAD_INPUT_FILE], + LINES_INPUT, + "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", + "", + 2, + ); } #[test] @@ -482,7 +488,13 @@ fn test_extended_regexp_no_messages_without_error_02() { #[test] fn test_extended_regexp_no_messages_with_error_01() { - grep_test(&["-E", "-s", ERE, "-", BAD_INPUT_FILE], LINES_INPUT, "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", "", 2); + grep_test( + &["-E", "-s", ERE, "-", BAD_INPUT_FILE], + LINES_INPUT, + "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", + "", + 2, + ); } #[test] @@ -729,7 +741,13 @@ fn test_fixed_strings_no_messages_without_error_02() { #[test] fn test_fixed_strings_no_messages_with_error_01() { - grep_test(&["-F", "-s", FIXED, "-", BAD_INPUT_FILE], LINES_INPUT, "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", "", 2); + grep_test( + &["-F", "-s", FIXED, "-", BAD_INPUT_FILE], + LINES_INPUT, + "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", + "", + 2, + ); } #[test] @@ -816,12 +834,12 @@ fn test_fixed_strings_line_regexp_02() { #[test] fn test_fixed_strings_option_combination() { grep_test( - &["-F", "-insvx", FIXED], - LINES_INPUT, - "1:line_{1}\n2:p_line_{2}_s\n3: line_{3} \n4:LINE_{4}\n5:p_LINE_{5}_s\n6:l_{6}\n7:line_{70}\n", - "", - 0, - ); + &["-F", "-insvx", FIXED], + LINES_INPUT, + "1:line_{1}\n2:p_line_{2}_s\n3: line_{3} \n4:LINE_{4}\n5:p_LINE_{5}_s\n6:l_{6}\n7:line_{70}\n", + "", + 0, + ); } #[test] @@ -913,12 +931,12 @@ fn test_single_stdin() { #[test] fn test_duplicate_stdin() { grep_test( - &[BRE, "-", "-", "-"], - LINES_INPUT, - "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", - "", - 0, - ); + &[BRE, "-", "-", "-"], + LINES_INPUT, + "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\n", + "", + 0, + ); } #[test] @@ -951,23 +969,23 @@ fn test_duplicate_stdin_quiet() { #[test] fn test_duplicate_stdin_line_number() { grep_test( - &["-n", BRE, "-", "-", "-"], - LINES_INPUT, - "(standard input):1:line_{1}\n(standard input):2:p_line_{2}_s\n(standard input):3: line_{3} \n(standard input):7:line_{70}\n", - "", - 0, - ); + &["-n", BRE, "-", "-", "-"], + LINES_INPUT, + "(standard input):1:line_{1}\n(standard input):2:p_line_{2}_s\n(standard input):3: line_{3} \n(standard input):7:line_{70}\n", + "", + 0, + ); } #[test] fn test_stdin_and_file_input() { grep_test( - &[BRE, "-", INPUT_FILE_1, INPUT_FILE_2], - LINES_INPUT, - "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\ntests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\n", - "", - 0, - ); + &[BRE, "-", INPUT_FILE_1, INPUT_FILE_2], + LINES_INPUT, + "(standard input):line_{1}\n(standard input):p_line_{2}_s\n(standard input): line_{3} \n(standard input):line_{70}\ntests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\n", + "", + 0, + ); } #[test] @@ -1005,13 +1023,24 @@ fn test_stdin_and_input_files_quiet() { #[test] fn test_stdin_and_input_files_other_options() { - grep_test(&["-insvx", BRE, "-", INPUT_FILE_1, BAD_INPUT_FILE], LINES_INPUT, "(standard input):2:p_line_{2}_s\n(standard input):3: line_{3} \n(standard input):5:p_LINE_{5}_s\n(standard input):6:l_{6}\ntests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_1:3: line_{3} \ntests/grep/f_1:5:p_LINE_{5}_s\ntests/grep/f_1:6:l_{6}\n", "", 2); + grep_test( + &["-insvx", BRE, "-", INPUT_FILE_1, BAD_INPUT_FILE], + LINES_INPUT, + "(standard input):2:p_line_{2}_s\n(standard input):3: line_{3} \n(standard input):5:p_LINE_{5}_s\n(standard input):6:l_{6}\ntests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_1:3: line_{3} \ntests/grep/f_1:5:p_LINE_{5}_s\ntests/grep/f_1:6:l_{6}\n", + "", + 2, + ); } #[test] fn test_multiple_input_files() { - grep_test(&[r#"2[[:punct:]]"#, INPUT_FILE_1, INPUT_FILE_2, INPUT_FILE_3], LINES_INPUT, - "tests/grep/f_1:p_line_{2}_s\ntests/grep/f_2:void func2() {\ntests/grep/f_2: printf(\"This is function 2\\n\");\n", "", 0); + grep_test( + &[r#"2[[:punct:]]"#, INPUT_FILE_1, INPUT_FILE_2, INPUT_FILE_3], + LINES_INPUT, + "tests/grep/f_1:p_line_{2}_s\ntests/grep/f_2:void func2() {\ntests/grep/f_2: printf(\"This is function 2\\n\");\n", + "", + 0, + ); } #[test] @@ -1067,8 +1096,19 @@ fn test_multiple_input_files_quiet() { #[test] fn test_multiple_input_files_line_number() { - grep_test(&["-n", r#"2[[:punct:]]"#, INPUT_FILE_1, INPUT_FILE_2, INPUT_FILE_3], LINES_INPUT, - "tests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_2:12:void func2() {\ntests/grep/f_2:13: printf(\"This is function 2\\n\");\n", "", 0); + grep_test( + &[ + "-n", + r#"2[[:punct:]]"#, + INPUT_FILE_1, + INPUT_FILE_2, + INPUT_FILE_3, + ], + LINES_INPUT, + "tests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_2:12:void func2() {\ntests/grep/f_2:13: printf(\"This is function 2\\n\");\n", + "", + 0, + ); } #[test] @@ -1117,7 +1157,21 @@ fn test_duplicate_input_files_quiet() { #[test] fn test_multiple_pattern_files_multiple_input_files() { - grep_test(&["-f", BRE_FILE_1, "-f", BRE_FILE_2, INPUT_FILE_1, INPUT_FILE_2, INPUT_FILE_3], LINES_INPUT, "tests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\ntests/grep/f_2:#include \ntests/grep/f_2:void func1() {\ntests/grep/f_2:void func2() {\n", "", 0); + grep_test( + &[ + "-f", + BRE_FILE_1, + "-f", + BRE_FILE_2, + INPUT_FILE_1, + INPUT_FILE_2, + INPUT_FILE_3, + ], + LINES_INPUT, + "tests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\ntests/grep/f_2:#include \ntests/grep/f_2:void func1() {\ntests/grep/f_2:void func2() {\n", + "", + 0, + ); } #[test] @@ -1182,7 +1236,22 @@ fn test_multiple_pattern_files_multiple_input_files_quiet() { #[test] fn test_multiple_pattern_files_multiple_input_files_line_number() { - grep_test(&["-n", "-f", BRE_FILE_1, "-f", BRE_FILE_2, INPUT_FILE_1, INPUT_FILE_2, INPUT_FILE_3], LINES_INPUT, "tests/grep/f_1:1:line_{1}\ntests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_1:3: line_{3} \ntests/grep/f_1:7:line_{70}\ntests/grep/f_2:1:#include \ntests/grep/f_2:8:void func1() {\ntests/grep/f_2:12:void func2() {\n", "", 0); + grep_test( + &[ + "-n", + "-f", + BRE_FILE_1, + "-f", + BRE_FILE_2, + INPUT_FILE_1, + INPUT_FILE_2, + INPUT_FILE_3, + ], + LINES_INPUT, + "tests/grep/f_1:1:line_{1}\ntests/grep/f_1:2:p_line_{2}_s\ntests/grep/f_1:3: line_{3} \ntests/grep/f_1:7:line_{70}\ntests/grep/f_2:1:#include \ntests/grep/f_2:8:void func1() {\ntests/grep/f_2:12:void func2() {\n", + "", + 0, + ); } #[test] @@ -1377,15 +1446,10 @@ fn test_regexp_long_names_regexes() { #[test] fn test_long_names_files() { grep_test( - &[ - "--file", - BRE_FILE_1, - INPUT_FILE_1, - INPUT_FILE_2, - ], - LINES_INPUT, - "tests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\n", - "", - 0, - ); + &["--file", BRE_FILE_1, INPUT_FILE_1, INPUT_FILE_2], + LINES_INPUT, + "tests/grep/f_1:line_{1}\ntests/grep/f_1:p_line_{2}_s\ntests/grep/f_1: line_{3} \ntests/grep/f_1:line_{70}\n", + "", + 0, + ); } diff --git a/text/tests/head/mod.rs b/text/tests/head/mod.rs index e739ff34d..26d6a37c7 100644 --- a/text/tests/head/mod.rs +++ b/text/tests/head/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use rand::{seq::SliceRandom, thread_rng}; /* #region Normal tests */ diff --git a/text/tests/join/mod.rs b/text/tests/join/mod.rs index b95564ca9..e352ae6a8 100644 --- a/text/tests/join/mod.rs +++ b/text/tests/join/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn run_test_join( args: &[&str], diff --git a/text/tests/nl/mod.rs b/text/tests/nl/mod.rs index 151423b25..a8d950b6b 100644 --- a/text/tests/nl/mod.rs +++ b/text/tests/nl/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn nl_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tests/paste/mod.rs b/text/tests/paste/mod.rs index b7883e833..4eba4b8b1 100644 --- a/text/tests/paste/mod.rs +++ b/text/tests/paste/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_u8, TestPlan, TestPlanU8}; +use plib::testing::{TestPlan, TestPlanU8, run_test, run_test_u8}; use std::fs; use std::path::PathBuf; diff --git a/text/tests/pr/mod.rs b/text/tests/pr/mod.rs index 18ad60066..c98b2bcd8 100644 --- a/text/tests/pr/mod.rs +++ b/text/tests/pr/mod.rs @@ -9,7 +9,7 @@ // use chrono::{DateTime, Local}; -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; use regex::Regex; use std::fs; use std::io::Read; diff --git a/text/tests/sed/mod.rs b/text/tests/sed/mod.rs index 8f4048d51..2a791ed0b 100644 --- a/text/tests/sed/mod.rs +++ b/text/tests/sed/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn sed_test( args: &[&str], @@ -500,18 +500,78 @@ mod tests { fn test_address_correct() { let test_data = [ // correct - ("1,10 p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", ""), - ("1,10p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", ""), - ("1,10 p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", ""), - ("10 p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nt\nw\nq\nh\nw\n", ""), - ("1,$p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nw\nq\nq\nh\nh\nw\nw\n", ""), - ("1,$ p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nw\nq\nq\nh\nh\nw\nw\n", ""), - ("$ p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", ""), - ("$ p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", ""), - ("$,$p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", ""), - ("$,$ p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", ""), - ("1, 10 p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", ""), - ("1 ,10 p", "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", "") + ( + "1,10 p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), + ( + "1,10p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), + ( + "1,10 p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), + ( + "10 p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), + ( + "1,$p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nw\nq\nq\nh\nh\nw\nw\n", + "", + ), + ( + "1,$ p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nw\nq\nq\nh\nh\nw\nw\n", + "", + ), + ( + "$ p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", + "", + ), + ( + "$ p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", + "", + ), + ( + "$,$p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", + "", + ), + ( + "$,$ p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\nw\n", + "", + ), + ( + "1, 10 p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), + ( + "1 ,10 p", + "a\nb\nc\nd\ne\nf\ng\nm\nn\nt\nw\nq\nh\nw\n", + "a\na\nb\nb\nc\nc\nd\nd\ne\ne\nf\nf\ng\ng\nm\nm\nn\nn\nt\nt\nw\nq\nh\nw\n", + "", + ), ]; for (script, input, output, err) in test_data { @@ -1495,9 +1555,24 @@ mod tests { ("r aer", "abc\ncdf", "abc\ncdf\n", ""), ("r./text/ard/assets/abc", "abc\ncdf", "abc\ncdf\n", ""), // wrong - ("r", "abc\ncdf", "", "sed: missing filename in r/R/w/W commands (line: 0, col: 1)\n"), - ("r #@/?", "abc\ncdf", "", "sed: missing filename in r/R/w/W commands (line: 0, col: 2)\n"), - ("r #@/?\nl", "abc\ncdf", "", "sed: missing filename in r/R/w/W commands (line: 0, col: 2)\n") + ( + "r", + "abc\ncdf", + "", + "sed: missing filename in r/R/w/W commands (line: 0, col: 1)\n", + ), + ( + "r #@/?", + "abc\ncdf", + "", + "sed: missing filename in r/R/w/W commands (line: 0, col: 2)\n", + ), + ( + "r #@/?\nl", + "abc\ncdf", + "", + "sed: missing filename in r/R/w/W commands (line: 0, col: 2)\n", + ), ]; for (script, input, output, err) in test_data { @@ -1825,7 +1900,12 @@ mod tests { fn test_w() { let test_data = [ // correct - ("w ./tests/sed/assets/newfile", "abc\ncdf\n", "abc\ncdf\n", ""), + ( + "w ./tests/sed/assets/newfile", + "abc\ncdf\n", + "abc\ncdf\n", + "", + ), ("w atyfv", "abc\ncdf\n", "abc\ncdf\n", ""), ("w./tests/sed/assets/r", "", "", ""), ("w./tests/sed/assets/newfile", "a\n", "a\n", ""), @@ -1996,18 +2076,62 @@ mod tests { fn test_combinations_1() { let test_data = [ // correct - (":x ; \\/=$/ { N ; s/=$=//g ; bx }", "abc=$=\ncdf=$=\nret=$=\nget=$=\n", "abc\ncdf\nret\nget\n", ""), - ("1,3 { p ; p } ; 1,2 { p ; p } ; {p ; p}", "abc\ncdf\nret\nget\n", - "abc\nabc\nabc\nabc\nabc\nabc\nabc\ncdf\ncdf\ncdf\ncdf\ncdf\ncdf\ncdf\nret\nret\nret\nret\nret\nget\nget\nget\n", ""), + ( + ":x ; \\/=$/ { N ; s/=$=//g ; bx }", + "abc=$=\ncdf=$=\nret=$=\nget=$=\n", + "abc\ncdf\nret\nget\n", + "", + ), + ( + "1,3 { p ; p } ; 1,2 { p ; p } ; {p ; p}", + "abc\ncdf\nret\nget\n", + "abc\nabc\nabc\nabc\nabc\nabc\nabc\ncdf\ncdf\ncdf\ncdf\ncdf\ncdf\ncdf\nret\nret\nret\nret\nret\nget\nget\nget\n", + "", + ), ("\\/1/b else ; s/a/z/ ; :else ; y/123/456/", "", "", ""), - ("\\/1/s/a/z/ ; y/123/456/", "1aaa\n123aa\n", "4zaa\n456za\n", ""), - ("\\/start/,\\/end/p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nqwerty\n", ""), - ("\\/start/,$p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", ""), - ("1,\\/end/p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", "a\na\nb\nb\nc\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nqwerty\n", ""), - ("2,4 !p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", "a\na\nb\nc\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", ""), - ("2,4 !{p}", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", "a\na\nb\nc\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", ""), + ( + "\\/1/s/a/z/ ; y/123/456/", + "1aaa\n123aa\n", + "4zaa\n456za\n", + "", + ), + ( + "\\/start/,\\/end/p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nqwerty\n", + "", + ), + ( + "\\/start/,$p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", + "", + ), + ( + "1,\\/end/p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\na\nb\nb\nc\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nqwerty\n", + "", + ), + ( + "2,4 !p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\na\nb\nc\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", + "", + ), + ( + "2,4 !{p}", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\na\nb\nc\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", + "", + ), //wrong - ("\\/pattern/- p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty", "", "sed: unknown character '-' (line: 0, col: 11)\n") + ( + "\\/pattern/- p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty", + "", + "sed: unknown character '-' (line: 0, col: 11)\n", + ), ]; for (script, input, output, err) in test_data { @@ -2019,18 +2143,42 @@ mod tests { fn test_combinations_2() { let test_data = [ // correct - (r#"s/^[^[:space:]]*[[:space:]]*//"#, "apple pie is sweet\n123abc test123\nhello world\n", - "pie is sweet\ntest123\nworld\n", ""), - (r#"s/^[[:alnum:]]*[[:space:]]*//"#, "apple pie is sweet\n123abc test123\nhello world\n", - "pie is sweet\ntest123\nworld\n", ""), - (r#"s/\([[:alnum:]]*\)/\1/1"#, "apple pie is sweet\n123abc test123\nhello world\n", - "apple pie is sweet\n123abc test123\nhello world\n", ""), - ("\\:start:,\\,stop, p", "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", - "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", ""), - ("\\`'$PATTERN'`p", "'$PATTERN'\nabc\n\n'$PATTERN'\nret'$PATTERN'abc\n", - "'$PATTERN'\n'$PATTERN'\nabc\n\n'$PATTERN'\n'$PATTERN'\nret'$PATTERN'abc\nret'$PATTERN'abc\n", ""), - ("s/param=.*/param=new_value\n/", "param=abc\nparam=\nparam abc\n", - "", "sed: unterminated `s' command (line: 0, col: 3)\n"), + ( + r#"s/^[^[:space:]]*[[:space:]]*//"#, + "apple pie is sweet\n123abc test123\nhello world\n", + "pie is sweet\ntest123\nworld\n", + "", + ), + ( + r#"s/^[[:alnum:]]*[[:space:]]*//"#, + "apple pie is sweet\n123abc test123\nhello world\n", + "pie is sweet\ntest123\nworld\n", + "", + ), + ( + r#"s/\([[:alnum:]]*\)/\1/1"#, + "apple pie is sweet\n123abc test123\nhello world\n", + "apple pie is sweet\n123abc test123\nhello world\n", + "", + ), + ( + "\\:start:,\\,stop, p", + "a\nb\nc\nstart\nt\n\nu\nend\nert\nqwerty\n", + "a\nb\nc\nstart\nstart\nt\nt\n\n\nu\nu\nend\nend\nert\nert\nqwerty\nqwerty\n", + "", + ), + ( + "\\`'$PATTERN'`p", + "'$PATTERN'\nabc\n\n'$PATTERN'\nret'$PATTERN'abc\n", + "'$PATTERN'\n'$PATTERN'\nabc\n\n'$PATTERN'\n'$PATTERN'\nret'$PATTERN'abc\nret'$PATTERN'abc\n", + "", + ), + ( + "s/param=.*/param=new_value\n/", + "param=abc\nparam=\nparam abc\n", + "", + "sed: unterminated `s' command (line: 0, col: 3)\n", + ), ]; for (script, input, output, err) in test_data { @@ -2162,24 +2310,61 @@ mod tests { fn test_combinations_5() { let test_data = [ // correct - ("\\/./,\\/^$/p", "\n\nline1\nline2\n\nline3\n", "\n\nline1\nline1\nline2\nline2\n\n\nline3\nline3\n", ""), - ("\\/string [[:digit:]]* /p", "string 123 \nstring abc \nstring 456 \n", - "string 123 \nstring 123 \nstring abc \nstring 456 \nstring 456 \n", ""), - ("\\/,.*/ p", "hello, world\nhello world\n\n", "hello, world\nhello, world\nhello world\n\n", ""), - ("\\:ac: p", ":ac:\n:bc:\n:ac:\n", ":ac:\n:ac:\n:bc:\n:ac:\n:ac:\n", ""), - ("1,\\,stop, p", "first line\nsecond stop\nthird line\n", "first line\nfirst line\nsecond stop\nsecond stop\nthird line\n", ""), - ("s/WORD/Hello World/p ; p", "WORD is here\nthis is not word\n", - "Hello World is here\nHello World is here\nHello World is here\nthis is not word\nthis is not word\n", ""), - ("s/SUBST/program\\/lib\\/module\\/lib.so/", "this is a test SUBST\nwe use SUBST here as well", - "this is a test program/lib/module/lib.so\nwe use program/lib/module/lib.so here as well", ""), - ("s/.*/[&]/", "This is a test\nAnother test line\n", "[This is a test]\n[Another test line]\n", ""), + ( + "\\/./,\\/^$/p", + "\n\nline1\nline2\n\nline3\n", + "\n\nline1\nline1\nline2\nline2\n\n\nline3\nline3\n", + "", + ), + ( + "\\/string [[:digit:]]* /p", + "string 123 \nstring abc \nstring 456 \n", + "string 123 \nstring 123 \nstring abc \nstring 456 \nstring 456 \n", + "", + ), + ( + "\\/,.*/ p", + "hello, world\nhello world\n\n", + "hello, world\nhello, world\nhello world\n\n", + "", + ), + ( + "\\:ac: p", + ":ac:\n:bc:\n:ac:\n", + ":ac:\n:ac:\n:bc:\n:ac:\n:ac:\n", + "", + ), + ( + "1,\\,stop, p", + "first line\nsecond stop\nthird line\n", + "first line\nfirst line\nsecond stop\nsecond stop\nthird line\n", + "", + ), + ( + "s/WORD/Hello World/p ; p", + "WORD is here\nthis is not word\n", + "Hello World is here\nHello World is here\nHello World is here\nthis is not word\nthis is not word\n", + "", + ), + ( + "s/SUBST/program\\/lib\\/module\\/lib.so/", + "this is a test SUBST\nwe use SUBST here as well", + "this is a test program/lib/module/lib.so\nwe use program/lib/module/lib.so here as well", + "", + ), + ( + "s/.*/[&]/", + "This is a test\nAnother test line\n", + "[This is a test]\n[Another test line]\n", + "", + ), // wrong ( - r#"s/#.*//;s/[[:blank:]]*$//;\/^$/ d;p"#, - "# This is a comment\nLine with trailing spaces \nAnother line\n", - "Line with trailing spaces\nLine with trailing spaces\nAnother line\nAnother line\n", - "" - ) + r#"s/#.*//;s/[[:blank:]]*$//;\/^$/ d;p"#, + "# This is a comment\nLine with trailing spaces \nAnother line\n", + "Line with trailing spaces\nLine with trailing spaces\nAnother line\nAnother line\n", + "", + ), ]; for (script, input, output, err) in test_data { @@ -2249,23 +2434,54 @@ mod tests { #[test] fn test_combinations_7() { let test_data = [ - // correct - (r#"\/^Reply-To:/q; \/^From:/h; \/./d;g;q"#, "From: someone\nReply-To: someoneelse\n", "Reply-To: someoneelse\n", ""), - ("\\/./{H;$d}; x; 1 s/^/START-->/; $ s/$/<--END/", "Line 1\nLine 2\n\nLine 3", - "START-->\nLine 1\nLine 1\nLine 2\nLine 2\n", ""), - (r#"1 s/^/ /; $ s/$/ /"#, "line1\nline2", " line1\nline2 ", ""), - (":a; $ q; n; 11,$ D; ba", "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\nline9\nline10\nline11\nline12\n", - "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\nline9\nline10\nline12\n", ""), - (r#"$ s/[[:alnum:]]*//2"#, "apple pie is sweet\n123abc test123 hello world\none two three four\n", - "apple pie is sweet\n123abc test123 hello world\none three four\n", ""), - (r#"s/[[:alnum:]]*//2"#, "apple pie is sweet\n123abc test123 hello world\none two three four\n", - "apple is sweet\n123abc hello world\none three four\n", ""), - (r#":a;s/^.\{1,13\}$/ &/;ta"#, "12345678\n1234567890123", " 12345678\n 1234567890123", ""), + // correct + ( + r#"\/^Reply-To:/q; \/^From:/h; \/./d;g;q"#, + "From: someone\nReply-To: someoneelse\n", + "Reply-To: someoneelse\n", + "", + ), + ( + "\\/./{H;$d}; x; 1 s/^/START-->/; $ s/$/<--END/", + "Line 1\nLine 2\n\nLine 3", + "START-->\nLine 1\nLine 1\nLine 2\nLine 2\n", + "", + ), + ( + r#"1 s/^/ /; $ s/$/ /"#, + "line1\nline2", + " line1\nline2 ", + "", + ), + ( + ":a; $ q; n; 11,$ D; ba", + "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\nline9\nline10\nline11\nline12\n", + "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\nline9\nline10\nline12\n", + "", + ), + ( + r#"$ s/[[:alnum:]]*//2"#, + "apple pie is sweet\n123abc test123 hello world\none two three four\n", + "apple pie is sweet\n123abc test123 hello world\none three four\n", + "", + ), + ( + r#"s/[[:alnum:]]*//2"#, + "apple pie is sweet\n123abc test123 hello world\none two three four\n", + "apple is sweet\n123abc hello world\none three four\n", + "", + ), + ( + r#":a;s/^.\{1,13\}$/ &/;ta"#, + "12345678\n1234567890123", + " 12345678\n 1234567890123", + "", + ), ( "\\/begin/,\\/end/ {\ns/#.* //;\n\ns/[[:blank:]]*$//;\n\\/^$/ d;\np;\n}", "Some text\nbegin\n# A comment \nLine with trailing spaces \nAnother line\n\n \nend\nSome more text\n", - "Some text\nbegin\nbegin\nLine with trailing spaces\nLine with trailing spaces\nAnother line\nAnother line\nend\nend\nSome more text\n", - "" + "Some text\nbegin\nbegin\nLine with trailing spaces\nLine with trailing spaces\nAnother line\nAnother line\nend\nend\nSome more text\n", + "", ), ]; for (script, input, output, err) in test_data { diff --git a/text/tests/sort/mod.rs b/text/tests/sort/mod.rs index 1474283e7..8a80d5c5b 100644 --- a/text/tests/sort/mod.rs +++ b/text/tests/sort/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn sort_test( args: &[&str], @@ -606,10 +606,10 @@ fn test_files_sort_1() { #[test] fn test_files_sort_2() { sort_test( - &["-n", "tests/assets/in_seq", "tests/assets/test_file.txt"], - "", - "1\n1sdfghnm\n2\n2sadsgdhjmf\n3\n3zcxbncvm vbm\n4\n4asdbncv\n5\n5adsbfdgfnfm\n6\n6sdfcvncbmcg\n7zsdgdgfndcgmncg\n8asdbsfdndcgmn\n9sfbdxgfndcgmncgmn\n10dvsd\n11\n12\n13\n14\n15\n16\n17\n", - 0, - "", - ); + &["-n", "tests/assets/in_seq", "tests/assets/test_file.txt"], + "", + "1\n1sdfghnm\n2\n2sadsgdhjmf\n3\n3zcxbncvm vbm\n4\n4asdbncv\n5\n5adsbfdgfnfm\n6\n6sdfcvncbmcg\n7zsdgdgfndcgmncg\n8asdbsfdndcgmn\n9sfbdxgfndcgmncgmn\n10dvsd\n11\n12\n13\n14\n15\n16\n17\n", + 0, + "", + ); } diff --git a/text/tests/tail/mod.rs b/text/tests/tail/mod.rs index 1b316c20a..ebc5e896f 100644 --- a/text/tests/tail/mod.rs +++ b/text/tests/tail/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_u8, TestPlan, TestPlanU8}; +use plib::testing::{TestPlan, TestPlanU8, run_test, run_test_u8}; fn tail_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args = args.iter().map(|st| (*st).to_owned()).collect::>(); diff --git a/text/tests/tr/mod.rs b/text/tests/tr/mod.rs index 1dde94878..0cc4b0ce2 100644 --- a/text/tests/tr/mod.rs +++ b/text/tests/tr/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_u8, TestPlan, TestPlanU8}; +use plib::testing::{TestPlan, TestPlanU8, run_test, run_test_u8}; fn tr_test_binary(args: &[&str], test_data: &[u8], expected_output: &[u8]) { let str_args = args diff --git a/text/tests/unexpand/mod.rs b/text/tests/unexpand/mod.rs index 31d40f0c1..7e0a09211 100644 --- a/text/tests/unexpand/mod.rs +++ b/text/tests/unexpand/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn unexpand_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tests/uniq/mod.rs b/text/tests/uniq/mod.rs index e94d06262..405a0ef75 100644 --- a/text/tests/uniq/mod.rs +++ b/text/tests/uniq/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn uniq_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tests/wc/mod.rs b/text/tests/wc/mod.rs index 0b8a20e1f..a80b16de3 100644 --- a/text/tests/wc/mod.rs +++ b/text/tests/wc/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn wc_test(args: &[&str], test_data: &str, expected_output: &str) { let str_args: Vec = args.iter().map(|s| String::from(*s)).collect(); diff --git a/text/tr.rs b/text/tr.rs index 276b72d39..07a00442e 100644 --- a/text/tr.rs +++ b/text/tr.rs @@ -1,5 +1,5 @@ use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use setup::{ForRemoval, ForTranslation}; use std::error::Error; use std::process; @@ -607,7 +607,9 @@ mod parsing { let parse_single_char_result = parse_single_char(&mut peekable)?; let Some(char) = parse_single_char_result else { - return Err(format!("could not parse [x*n] construct: bad input near \"{square_bracket_constructs_buffer_string}\"")); + return Err(format!( + "could not parse [x*n] construct: bad input near \"{square_bracket_constructs_buffer_string}\"" + )); }; // Skip '*' @@ -733,8 +735,8 @@ mod parsing { match u8::from_str_radix(chars_str, 8_u32) { Ok(ue) => { eprintln!( - "tr: warning: the ambiguous octal escape \\{st} is being interpreted as the 2-byte sequence \\0{chars_str}, {third_octal_digit}" - ); + "tr: warning: the ambiguous octal escape \\{st} is being interpreted as the 2-byte sequence \\0{chars_str}, {third_octal_digit}" + ); ue } @@ -978,7 +980,7 @@ mod parsing { st => { return Err(format!( "input '[:{st}:]' is invalid: invalid character class '{st}'" - )) + )); } }; @@ -1229,8 +1231,7 @@ mod setup { match op { Operand::Char(CharOperand { - ref mut char_repetition, - .. + char_repetition, .. }) => { *char_repetition = CharRepetition::N(leftover); } @@ -1244,7 +1245,7 @@ mod setup { for op in vec.iter_mut().rev() { if let Operand::Char(CharOperand { - char_repetition: CharRepetition::N(ref mut n), + char_repetition: CharRepetition::N(n), .. }) = op { diff --git a/text/tsort.rs b/text/tsort.rs index 0836e4264..9e3e6cdff 100644 --- a/text/tsort.rs +++ b/text/tsort.rs @@ -11,7 +11,7 @@ use std::io::{self, BufRead}; use std::path::PathBuf; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::io::input_stream_opt; use topological_sort::TopologicalSort; diff --git a/text/unexpand.rs b/text/unexpand.rs index 76a930bae..993f366e7 100644 --- a/text/unexpand.rs +++ b/text/unexpand.rs @@ -1,5 +1,5 @@ use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::io::{self, BufRead, Write}; use std::path::PathBuf; diff --git a/text/uniq.rs b/text/uniq.rs index 33d2575a2..e11714660 100644 --- a/text/uniq.rs +++ b/text/uniq.rs @@ -1,5 +1,5 @@ use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::fs::File; use std::io::{self, BufRead, BufReader, Write}; use std::path::PathBuf; diff --git a/text/wc.rs b/text/wc.rs index 807b15fdd..983121ff4 100644 --- a/text/wc.rs +++ b/text/wc.rs @@ -15,9 +15,9 @@ use std::{ }; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; /// wc - word, line, and byte or character count #[derive(Parser)] diff --git a/tree/chgrp.rs b/tree/chgrp.rs index 77a8806a8..20cf5ada4 100644 --- a/tree/chgrp.rs +++ b/tree/chgrp.rs @@ -11,7 +11,7 @@ mod common; use self::common::error_string; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::{cell::RefCell, ffi::CString, io, os::unix::fs::MetadataExt}; /// chgrp - change file group ownership diff --git a/tree/chmod.rs b/tree/chmod.rs index d9fa17a87..cd94f5801 100644 --- a/tree/chmod.rs +++ b/tree/chmod.rs @@ -11,7 +11,7 @@ mod common; use self::common::error_string; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use modestr::ChmodMode; use plib::modestr; use std::{cell::RefCell, io, os::unix::fs::MetadataExt}; diff --git a/tree/chown.rs b/tree/chown.rs index cf5e3e2c1..fa52fe821 100644 --- a/tree/chown.rs +++ b/tree/chown.rs @@ -11,7 +11,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::ffi::CString; use std::os::unix::fs::MetadataExt; use std::path::Path; diff --git a/tree/cp.rs b/tree/cp.rs index 82abc6582..f40415b2f 100644 --- a/tree/cp.rs +++ b/tree/cp.rs @@ -9,9 +9,9 @@ mod common; -use self::common::{copy_file, copy_files, error_string, CopyConfig}; +use self::common::{CopyConfig, copy_file, copy_files, error_string}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::collections::HashSet; use std::path::PathBuf; use std::{fs, io}; diff --git a/tree/du.rs b/tree/du.rs index 5fe487b6f..0e92a2b11 100644 --- a/tree/du.rs +++ b/tree/du.rs @@ -11,7 +11,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::os::unix::fs::MetadataExt; use std::path::Path; use std::{fs, io}; @@ -49,11 +49,7 @@ struct Args { } fn calc_size(kilo: bool, size: u64) -> u64 { - if kilo { - size / 2 - } else { - size - } + if kilo { size / 2 } else { size } } fn print_pathinfo(args: &Args, filename: &str, size: u64, toplevel: bool) { diff --git a/tree/link.rs b/tree/link.rs index b3ad4da6b..0c88c1fc7 100644 --- a/tree/link.rs +++ b/tree/link.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::{fs, io}; /// link - call link function diff --git a/tree/ln.rs b/tree/ln.rs index 33e2b6074..2fb54a8aa 100644 --- a/tree/ln.rs +++ b/tree/ln.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::path::{Path, PathBuf}; use std::{fs, io}; diff --git a/tree/ls.rs b/tree/ls.rs index 0bea323b7..2df8a027f 100644 --- a/tree/ls.rs +++ b/tree/ls.rs @@ -9,9 +9,9 @@ mod ls_util; -use self::ls_util::{ls_from_utf8_lossy, Entry, LongFormatPadding, MultiColumnPadding}; +use self::ls_util::{Entry, LongFormatPadding, MultiColumnPadding, ls_from_utf8_lossy}; use clap::{CommandFactory, FromArgMatches, Parser}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::platform::P_WINSIZE_REQUEST_CODE; use std::{ collections::HashMap, diff --git a/tree/ls_util/entry.rs b/tree/ls_util/entry.rs index c85d223c0..8f2437be0 100644 --- a/tree/ls_util/entry.rs +++ b/tree/ls_util/entry.rs @@ -9,8 +9,8 @@ use super::ls_from_utf8_lossy; use crate::{ - ClassifyFiles, Config, FileTimeOption, LongFormatOptions, OutputFormat, - DATE_TIME_FORMAT_OLD_OR_FUTURE, DATE_TIME_FORMAT_RECENT, + ClassifyFiles, Config, DATE_TIME_FORMAT_OLD_OR_FUTURE, DATE_TIME_FORMAT_RECENT, FileTimeOption, + LongFormatOptions, OutputFormat, }; use chrono::{DateTime, Local}; use std::{ @@ -405,11 +405,7 @@ impl Entry { pub fn get_long_format_padding(&self) -> LongFormatPadding { // Calculate the length of the resulting string when `v` is converted. fn decimal_str_len(v: u64) -> usize { - if v == 0 { - 1 - } else { - v.ilog10() as usize + 1 - } + if v == 0 { 1 } else { v.ilog10() as usize + 1 } } let blocks_str_width = self.multi_column_padding.blocks_str_width; diff --git a/tree/mkdir.rs b/tree/mkdir.rs index 312069c5a..81cc9c97c 100644 --- a/tree/mkdir.rs +++ b/tree/mkdir.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use modestr::ChmodMode; use plib::modestr; use std::ffi::CString; diff --git a/tree/mkfifo.rs b/tree/mkfifo.rs index 86bc7e89f..e1d4cda89 100644 --- a/tree/mkfifo.rs +++ b/tree/mkfifo.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use modestr::ChmodMode; use plib::modestr; use std::io; diff --git a/tree/mv.rs b/tree/mv.rs index dbb4380d0..ac3740ec6 100644 --- a/tree/mv.rs +++ b/tree/mv.rs @@ -13,7 +13,7 @@ mod common; use self::common::{copy_file, error_string}; use clap::Parser; use common::CopyConfig; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::{ collections::{HashMap, HashSet}, ffi::CString, diff --git a/tree/readlink.rs b/tree/readlink.rs index 18ade5795..f26a2a55e 100644 --- a/tree/readlink.rs +++ b/tree/readlink.rs @@ -8,11 +8,11 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::error::Error; use std::fs; use std::io::Write; -use std::io::{stderr, stdout, ErrorKind}; +use std::io::{ErrorKind, stderr, stdout}; use std::path::PathBuf; use std::path::{Component, Path}; diff --git a/tree/rm.rs b/tree/rm.rs index 1437ca2f7..b6a0cd91b 100644 --- a/tree/rm.rs +++ b/tree/rm.rs @@ -12,7 +12,7 @@ mod common; use self::common::error_string; use clap::Parser; use ftw::{self, traverse_directory}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::{ ffi::CString, fs, diff --git a/tree/rmdir.rs b/tree/rmdir.rs index d4ba13c55..4eee9d86a 100644 --- a/tree/rmdir.rs +++ b/tree/rmdir.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::fs; use std::io::{self, Error, ErrorKind}; use std::path::Path; diff --git a/tree/tests/chgrp/mod.rs b/tree/tests/chgrp/mod.rs index 67975f932..139fe2681 100644 --- a/tree/tests/chgrp/mod.rs +++ b/tree/tests/chgrp/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{ ffi::{CStr, CString}, fs, io, diff --git a/tree/tests/chmod/mod.rs b/tree/tests/chmod/mod.rs index 7b02b6b00..b37bf4384 100644 --- a/tree/tests/chmod/mod.rs +++ b/tree/tests/chmod/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{ fs, os::unix::{self, fs::PermissionsExt}, diff --git a/tree/tests/cp/mod.rs b/tree/tests/cp/mod.rs index 6ccc0d97a..6d90048c7 100644 --- a/tree/tests/cp/mod.rs +++ b/tree/tests/cp/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::ffi::CString; use std::io::{Read, Write}; use std::os::unix::fs::FileTypeExt; diff --git a/tree/tests/link/mod.rs b/tree/tests/link/mod.rs index 31e12ef90..ecbef583f 100644 --- a/tree/tests/link/mod.rs +++ b/tree/tests/link/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; use std::fs; use std::io::Write; use std::path::PathBuf; diff --git a/tree/tests/ls/mod.rs b/tree/tests/ls/mod.rs index 284f18bd8..11a4a2ff5 100644 --- a/tree/tests/ls/mod.rs +++ b/tree/tests/ls/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; use regex::Regex; use std::ffi::CString; use std::fs; @@ -589,7 +589,8 @@ fn test_ls_size_align() { #[test] fn test_ls_time() { // This gets inherited by child processes - std::env::set_var("TZ", "UTC0"); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { std::env::set_var("TZ", "UTC0") }; let test_dir = &format!("{}/test_ls_time", env!("CARGO_TARGET_TMPDIR")); let a = &format!("{test_dir}/a"); diff --git a/tree/tests/mkdir/mod.rs b/tree/tests/mkdir/mod.rs index 50f964348..1295c7fac 100644 --- a/tree/tests/mkdir/mod.rs +++ b/tree/tests/mkdir/mod.rs @@ -8,11 +8,11 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; use std::fs; use std::path::Path; use std::process::Output; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; fn setup_test_env() -> (TempDir, String) { let temp_dir = tempdir().expect("Unable to create temporary directory"); diff --git a/tree/tests/mv/mod.rs b/tree/tests/mv/mod.rs index 01ff29b81..b6a2ae308 100644 --- a/tree/tests/mv/mod.rs +++ b/tree/tests/mv/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::ffi::CString; use std::fs::{self, Permissions}; use std::io::{self, Read, Write}; diff --git a/tree/tests/readlink/mod.rs b/tree/tests/readlink/mod.rs index 644b39e14..c803850ab 100644 --- a/tree/tests/readlink/mod.rs +++ b/tree/tests/readlink/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::fs::File; use std::io::Write; use std::os::unix::fs::symlink; diff --git a/tree/tests/rm/mod.rs b/tree/tests/rm/mod.rs index f8496dc39..364ceced6 100644 --- a/tree/tests/rm/mod.rs +++ b/tree/tests/rm/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; use std::ffi::CString; use std::fs; use std::io::{self, Write}; diff --git a/tree/tests/rmdir/mod.rs b/tree/tests/rmdir/mod.rs index de82ac455..5c12b43bd 100644 --- a/tree/tests/rmdir/mod.rs +++ b/tree/tests/rmdir/mod.rs @@ -8,11 +8,11 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test_with_checker}; use std::fs; use std::path::Path; use std::process::Output; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; fn setup_test_env() -> (TempDir, String) { let temp_dir = tempdir().expect("Unable to create temporary directory"); diff --git a/tree/tests/tree-tests-umask.rs b/tree/tests/tree-tests-umask.rs index f5bd4c331..795111c39 100644 --- a/tree/tests/tree-tests-umask.rs +++ b/tree/tests/tree-tests-umask.rs @@ -11,7 +11,7 @@ //! in `tree-tests.rs`. They are located here in `tree-tests-umask.rs` so that they can have a //! different per-process umask than those in `tree-tests.rs`. -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{ fs, os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}, diff --git a/tree/tests/unlink/mod.rs b/tree/tests/unlink/mod.rs index c60c96c6c..2669cb223 100644 --- a/tree/tests/unlink/mod.rs +++ b/tree/tests/unlink/mod.rs @@ -8,7 +8,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, run_test_with_checker, TestPlan}; +use plib::testing::{TestPlan, run_test, run_test_with_checker}; use std::fs; use tempfile::tempdir; diff --git a/tree/touch.rs b/tree/touch.rs index 10270e2ed..c2b52eeb2 100644 --- a/tree/touch.rs +++ b/tree/touch.rs @@ -9,7 +9,7 @@ use chrono::{DateTime, Datelike, LocalResult, TimeZone, Utc}; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; /// touch - change file access and modification times #[derive(Parser)] diff --git a/tree/unlink.rs b/tree/unlink.rs index ab682b557..53073fbf1 100644 --- a/tree/unlink.rs +++ b/tree/unlink.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::{fs, io}; /// unlink - call the unlink function diff --git a/users/id.rs b/users/id.rs index da36d4fe2..e731f191a 100644 --- a/users/id.rs +++ b/users/id.rs @@ -11,7 +11,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::group; use std::collections::HashMap; use std::io::Error; diff --git a/users/logger.rs b/users/logger.rs index 7c5cd5425..13a75f634 100644 --- a/users/logger.rs +++ b/users/logger.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use syslog::{Facility, Formatter3164}; fn main() -> Result<(), Box> { diff --git a/users/mesg.rs b/users/mesg.rs index aca96b812..32d456595 100644 --- a/users/mesg.rs +++ b/users/mesg.rs @@ -12,7 +12,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use std::io::{self, Error, ErrorKind, IsTerminal}; use std::mem; diff --git a/users/newgrp.rs b/users/newgrp.rs index a9623f0d0..59cdc87c7 100644 --- a/users/newgrp.rs +++ b/users/newgrp.rs @@ -7,8 +7,8 @@ // SPDX-License-Identifier: MIT // -use clap::{error::ErrorKind, Parser}; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use clap::{Parser, error::ErrorKind}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use libc::{ getgid, getgrnam, getgroups, getlogin, getpwnam, getpwuid, getuid, gid_t, passwd, setegid, setgid, setgroups, setuid, uid_t, @@ -767,11 +767,12 @@ fn set_login_environment(user: &str) -> Result<(), io::Error> { .unwrap_or("/bin/sh"); // Set the necessary environment variables - env::set_var("USER", user); - env::set_var("HOME", unsafe { - CStr::from_ptr(pwd.pw_dir).to_str().unwrap_or("") - }); - env::set_var("SHELL", user_shell); + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::set_var("USER", user) }; + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::set_var("HOME", CStr::from_ptr(pwd.pw_dir).to_str().unwrap_or("")) }; + // TODO: Audit that the environment access only happens in single-threaded code. + unsafe { env::set_var("SHELL", user_shell) }; let status = Command::new(user_shell) .env("USER", user) diff --git a/users/pwd.rs b/users/pwd.rs index 48fb74a4a..83fd02491 100644 --- a/users/pwd.rs +++ b/users/pwd.rs @@ -11,7 +11,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::ffi::OsStr; use std::path::{Component, Path}; diff --git a/users/talk.rs b/users/talk.rs index 3521970d2..6917daf00 100644 --- a/users/talk.rs +++ b/users/talk.rs @@ -6,17 +6,17 @@ // SPDX-License-Identifier: MIT // -use clap::{error::ErrorKind, Parser}; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use clap::{Parser, error::ErrorKind}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use thiserror::Error; -use binrw::{binrw, BinReaderExt, BinWrite, Endian}; +use binrw::{BinReaderExt, BinWrite, Endian, binrw}; #[cfg(target_os = "linux")] use libc::sa_family_t; use libc::{ - addrinfo, getaddrinfo, gethostname, getpid, getpwuid, getservbyname, getuid, ioctl, signal, - sockaddr_in, winsize, AF_INET, AI_CANONNAME, SIGINT, SIGPIPE, SIGQUIT, SOCK_DGRAM, - STDIN_FILENO, STDOUT_FILENO, TIOCGWINSZ, + AF_INET, AI_CANONNAME, SIGINT, SIGPIPE, SIGQUIT, SOCK_DGRAM, STDIN_FILENO, STDOUT_FILENO, + TIOCGWINSZ, addrinfo, getaddrinfo, gethostname, getpid, getpwuid, getservbyname, getuid, ioctl, + signal, sockaddr_in, winsize, }; use std::{ diff --git a/users/write.rs b/users/write.rs index 934cc362c..d8f24790d 100644 --- a/users/write.rs +++ b/users/write.rs @@ -9,7 +9,7 @@ use chrono::Local; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::{curuser, platform, utmpx}; use std::fs::{self, OpenOptions}; use std::io::{self, BufRead, Write}; diff --git a/xform/cksum.rs b/xform/cksum.rs index f63306bdf..3d35d432b 100644 --- a/xform/cksum.rs +++ b/xform/cksum.rs @@ -18,9 +18,9 @@ mod crc32; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use plib::io::input_stream; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::BUFSZ; +use plib::io::input_stream; use std::io::{self, Read}; use std::path::PathBuf; @@ -49,13 +49,7 @@ fn cksum_file(filename: &PathBuf) -> io::Result<()> { crc = crc32::update(crc, &buffer[0..n_read]); } - let filename_prefix = { - if filename.as_os_str() == "" { - "" - } else { - " " - } - }; + let filename_prefix = { if filename.as_os_str() == "" { "" } else { " " } }; println!( "{} {}{}{}", crc32::finalize(crc, n_bytes), diff --git a/xform/compress.rs b/xform/compress.rs index fd307e1e2..93689524a 100644 --- a/xform/compress.rs +++ b/xform/compress.rs @@ -8,7 +8,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, gettext, setlocale, textdomain}; use plib::io::input_stream; use plib::lzw::UnixLZWWriter; use std::fs::{self, File}; diff --git a/xform/tests/cksum/mod.rs b/xform/tests/cksum/mod.rs index 83cdbf5ee..aa2ae039b 100644 --- a/xform/tests/cksum/mod.rs +++ b/xform/tests/cksum/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; fn cksum_test(test_data: &str, expected_output: &str) { run_test(TestPlan { diff --git a/xform/tests/compress/mod.rs b/xform/tests/compress/mod.rs index cdd00915e..4494e6b5b 100644 --- a/xform/tests/compress/mod.rs +++ b/xform/tests/compress/mod.rs @@ -7,9 +7,9 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{ - fs::{remove_file, File}, + fs::{File, remove_file}, io::Read, }; diff --git a/xform/tests/uue/mod.rs b/xform/tests/uue/mod.rs index 022a39bcb..2614402c9 100644 --- a/xform/tests/uue/mod.rs +++ b/xform/tests/uue/mod.rs @@ -7,7 +7,7 @@ // SPDX-License-Identifier: MIT // -use plib::testing::{run_test, TestPlan}; +use plib::testing::{TestPlan, run_test}; use std::{ fs::{File, Permissions}, io::Read, diff --git a/xform/uncompress.rs b/xform/uncompress.rs index f438071c1..3f1deccd4 100644 --- a/xform/uncompress.rs +++ b/xform/uncompress.rs @@ -12,7 +12,7 @@ // use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use plib::io::input_stream; use plib::lzw::UnixLZWReader; use std::io::{self, Write}; diff --git a/xform/uudecode.rs b/xform/uudecode.rs index 566d9bce0..c2257d655 100644 --- a/xform/uudecode.rs +++ b/xform/uudecode.rs @@ -9,14 +9,14 @@ use base64::prelude::*; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; -use std::fs::{remove_file, File}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; +use std::fs::{File, remove_file}; use std::io::{self, Error, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; macro_rules! reduce { - ($e : expr) => { + ($e : expr_2021) => { $e - 0x20 }; } diff --git a/xform/uuencode.rs b/xform/uuencode.rs index b0a5e3984..63c528b29 100644 --- a/xform/uuencode.rs +++ b/xform/uuencode.rs @@ -9,7 +9,7 @@ use base64::prelude::*; use clap::Parser; -use gettextrs::{bind_textdomain_codeset, setlocale, textdomain, LocaleCategory}; +use gettextrs::{LocaleCategory, bind_textdomain_codeset, setlocale, textdomain}; use std::fs::{File, Permissions}; use std::io::{self, Read, Write}; use std::os::unix::fs::PermissionsExt;