1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

Merge branch 'main' into mktemp-set-dir-mode

This commit is contained in:
353fc443 aka Seagull 2022-05-02 10:24:03 +03:00 committed by GitHub
commit 3f942cddf5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 286 additions and 19 deletions

4
Cargo.lock generated
View file

@ -1608,9 +1608,9 @@ dependencies = [
[[package]]
name = "retain_mut"
version = "0.1.2"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53552c6c49e1e13f1a203ef0080ab3bbef0beb570a528993e83df057a9d9bba1"
checksum = "8c31b5c4033f8fdde8700e4657be2c497e7288f01515be52168c631e2e4d4086"
[[package]]
name = "rlimit"

View file

@ -80,7 +80,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let template = matches.value_of(ARG_TEMPLATE).unwrap();
let tmpdir = matches.value_of(OPT_TMPDIR).unwrap_or_default();
let (template, mut tmpdir) = if matches.is_present(OPT_TMPDIR)
// Treat the template string as a path to get the directory
// containing the last component.
let path = PathBuf::from(template);
let (template, tmpdir) = if matches.is_present(OPT_TMPDIR)
&& !PathBuf::from(tmpdir).is_dir() // if a temp dir is provided, it must be an actual path
&& tmpdir.contains("XXX")
// If this is a template, it has to contain at least 3 X
@ -98,8 +102,24 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let tmp = env::temp_dir();
(tmpdir, tmp)
} else if !matches.is_present(OPT_TMPDIR) {
let tmp = env::temp_dir();
(template, tmp)
// In this case, the command line was `mktemp -t XXX`, so we
// treat the argument `XXX` as though it were a filename
// regardless of whether it has path separators in it.
if matches.is_present(OPT_T) {
let tmp = env::temp_dir();
(template, tmp)
// In this case, the command line was `mktemp XXX`, so we need
// to parse out the parent directory and the filename from the
// argument `XXX`, since it may be include path separators.
} else {
let tmp = match path.parent() {
None => PathBuf::from("."),
Some(d) => PathBuf::from(d),
};
let filename = path.file_name();
let template = filename.unwrap().to_str().unwrap();
(template, tmp)
}
} else {
(template, PathBuf::from(tmpdir))
};
@ -114,10 +134,6 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
return Err(MkTempError::InvalidTemplate(template.into()).into());
}
if matches.is_present(OPT_T) {
tmpdir = env::temp_dir();
}
let res = if dry_run {
dry_exec(tmpdir, prefix, rand, suffix)
} else {
@ -273,8 +289,23 @@ fn exec(dir: &Path, prefix: &str, rand: usize, suffix: &str, make_dir: bool) ->
.map_err(|e| MkTempError::PersistError(e.file.path().to_path_buf()))?
.1
};
if make_dir {
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?;
}
// Get just the last component of the path to the created
// temporary file or directory.
let filename = path.file_name();
let filename = filename.unwrap().to_str().unwrap();
// Join the directory to the path to get the path to print. We
// cannot use the path returned by the `Builder` because it gives
// the absolute path and we need to return a filename that matches
// the template given on the command-line which might be a
// relative path.
let mut path = dir.to_path_buf();
path.push(filename);
println_verbatim(path).map_err_context(|| "failed to print directory name".to_owned())
}

View file

@ -5,7 +5,7 @@
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDOs) corasick memchr Roff trunc oset iset
// spell-checker:ignore (ToDOs) corasick memchr Roff trunc oset iset CHARCLASS
use clap::{crate_version, Arg, Command};
use regex::Regex;
@ -31,6 +31,8 @@ const ABOUT: &str = "\
Mandatory arguments to long options are mandatory for short options too.\n\
With no FILE, or when FILE is -, read standard input. Default is '-F /'.";
const REGEX_CHARCLASS: &str = "^-]\\";
#[derive(Debug)]
enum OutFormat {
Dumb,
@ -88,6 +90,18 @@ fn read_word_filter_file(
Ok(words)
}
/// reads contents of file as unique set of characters to be used with the break-file option
fn read_char_filter_file(
matches: &clap::ArgMatches,
option: &str,
) -> std::io::Result<HashSet<char>> {
let filename = matches.value_of(option).expect("parsing options failed!");
let mut reader = File::open(filename)?;
let mut buffer = String::new();
reader.read_to_string(&mut buffer)?;
Ok(buffer.chars().collect())
}
#[derive(Debug)]
struct WordFilter {
only_specified: bool,
@ -113,9 +127,23 @@ impl WordFilter {
} else {
(false, HashSet::new())
};
if matches.is_present(options::BREAK_FILE) {
return Err(PtxError::NotImplemented("-b").into());
}
let break_set: Option<HashSet<char>> = if matches.is_present(options::BREAK_FILE)
&& !matches.is_present(options::WORD_REGEXP)
{
let chars =
read_char_filter_file(matches, options::BREAK_FILE).map_err_context(String::new)?;
let mut hs: HashSet<char> = if config.gnu_ext {
HashSet::new() // really only chars found in file
} else {
// GNU off means at least these are considered
[' ', '\t', '\n'].iter().cloned().collect()
};
hs.extend(chars);
Some(hs)
} else {
// if -W takes precedence or default
None
};
// Ignore empty string regex from cmd-line-args
let arg_reg: Option<String> = if matches.is_present(options::WORD_REGEXP) {
match matches.value_of(options::WORD_REGEXP) {
@ -134,7 +162,21 @@ impl WordFilter {
let reg = match arg_reg {
Some(arg_reg) => arg_reg,
None => {
if config.gnu_ext {
if break_set.is_some() {
format!(
"[^{}]+",
break_set
.unwrap()
.into_iter()
.map(|c| if REGEX_CHARCLASS.contains(c) {
format!("\\{}", c)
} else {
c.to_string()
})
.collect::<Vec<String>>()
.join("")
)
} else if config.gnu_ext {
"\\w+".to_owned()
} else {
"[^ \t\n]+".to_owned()

View file

@ -17,7 +17,7 @@ path = "src/tee.rs"
[dependencies]
clap = { version = "3.1", features = ["wrap_help", "cargo"] }
libc = "0.2.124"
retain_mut = "=0.1.2" # ToDO: [2021-01-01; rivy; maint/MinSRV] ~ v0.1.5 uses const generics which aren't stabilized until rust v1.51.0
retain_mut = "=0.1.7" # ToDO: [2021-01-01; rivy; maint/MinSRV] ~ v0.1.5 uses const generics which aren't stabilized until rust v1.51.0
uucore = { version=">=0.0.11", package="uucore", path="../../uucore", features=["libc"] }
[[bin]]

View file

@ -31,7 +31,7 @@ fn test_default_output() {
scene
.ucmd()
.succeeds()
.stdout_does_not_match(&Regex::new("[rwx][^some-file1]").unwrap());
.stdout_does_not_match(&Regex::new("[rwx-]{10}.*some-file1$").unwrap());
}
#[test]
@ -51,5 +51,5 @@ fn test_long_output() {
.ucmd()
.arg("-l")
.succeeds()
.stdout_matches(&Regex::new("[rwx][^some-file1]").unwrap());
.stdout_matches(&Regex::new("[rwx-]{10}.*some-file1$").unwrap());
}

View file

@ -411,3 +411,74 @@ fn test_mktemp_directory_tmpdir() {
result.no_stderr().stdout_contains("apt-key-gpghome.");
assert!(PathBuf::from(result.stdout_str().trim()).is_dir());
}
/// Decide whether a string matches a given template.
///
/// In the template, the character `'X'` is treated as a wildcard,
/// that is, it matches anything. All other characters in `template`
/// and `s` must match exactly.
///
/// # Examples
///
/// ```rust,ignore
/// # These all match.
/// assert!(matches_template("abc", "abc"));
/// assert!(matches_template("aXc", "abc"));
/// assert!(matches_template("XXX", "abc"));
///
/// # None of these match
/// assert!(matches_template("abc", "abcd"));
/// assert!(matches_template("abc", "ab"));
/// assert!(matches_template("aXc", "abd"));
/// assert!(matches_template("XXX", "abcd"));
/// ```
///
fn matches_template(template: &str, s: &str) -> bool {
if template.len() != s.len() {
return false;
}
for (a, b) in template.chars().zip(s.chars()) {
if !(a == 'X' || a == b) {
return false;
}
}
true
}
/// An assertion that uses [`matches_template`] and adds a helpful error message.
macro_rules! assert_matches_template {
($template:expr, $s:expr) => {{
assert!(
matches_template($template, $s),
"\"{}\" != \"{}\"",
$template,
$s
);
}};
}
/// Test that the file is created in the directory given by the template.
#[test]
fn test_respect_template() {
let (at, mut ucmd) = at_and_ucmd!();
let template = "XXX";
let result = ucmd.arg(template).succeeds();
let filename = result.no_stderr().stdout_str().trim_end();
assert_matches_template!(template, filename);
assert!(at.file_exists(filename));
}
/// Test that the file is created in the directory given by the template.
#[test]
fn test_respect_template_directory() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("d");
#[cfg(not(windows))]
let template = "d/XXX";
#[cfg(windows)]
let template = r"d\XXX";
let result = ucmd.arg(template).succeeds();
let filename = result.no_stderr().stdout_str().trim_end();
assert_matches_template!(template, filename);
assert!(at.file_exists(filename));
}

View file

@ -71,3 +71,35 @@ fn gnu_ext_disabled_ignore_and_only_file() {
.succeeds()
.stdout_only_fixture("gnu_ext_disabled_ignore_and_only_file.expected");
}
#[test]
fn gnu_ext_disabled_output_width_50() {
new_ucmd!()
.args(&["-G", "-w", "50", "input"])
.succeeds()
.stdout_only_fixture("gnu_ext_disabled_output_width_50.expected");
}
#[test]
fn gnu_ext_disabled_output_width_70() {
new_ucmd!()
.args(&["-G", "-w", "70", "input"])
.succeeds()
.stdout_only_fixture("gnu_ext_disabled_output_width_70.expected");
}
#[test]
fn gnu_ext_disabled_break_file() {
new_ucmd!()
.args(&["-G", "-b", "break_file", "input"])
.succeeds()
.stdout_only_fixture("gnu_ext_disabled_break_file.expected");
}
#[test]
fn gnu_ext_disabled_empty_word_regexp_ignores_break_file() {
new_ucmd!()
.args(&["-G", "-b", "break_file", "-R", "-W", "", "input"])
.succeeds()
.stdout_only_fixture("gnu_ext_disabled_rightward_no_ref.expected");
}

View file

@ -31,7 +31,7 @@ fn test_default_output() {
scene
.ucmd()
.succeeds()
.stdout_matches(&Regex::new("[rwx][^some-file1]").unwrap());
.stdout_matches(&Regex::new("[rwx-]{10}.*some-file1$").unwrap());
}
#[test]
@ -51,5 +51,5 @@ fn test_column_output() {
.ucmd()
.arg("-C")
.succeeds()
.stdout_does_not_match(&Regex::new("[rwx][^some-file1]").unwrap());
.stdout_does_not_match(&Regex::new("[rwx-]{10}.*some-file1$").unwrap());
}

1
tests/fixtures/ptx/break_file vendored Normal file
View file

@ -0,0 +1 @@
abc_e^-]\

View file

@ -0,0 +1,42 @@
.xx "" "" """quotes"", for roff" ""
.xx "" "and some other like %a, b" "#, c$c" ""
.xx "" "and some other like %a, b#, c" "$c" ""
.xx "" "and some other like" "%a, b#, c$c" ""
.xx "" "and some other like %a" ", b#, c$c" ""
.xx "" """quotes""," "for roff" ""
.xx "" "{brackets}" "for tex" ""
.xx "" "" "hello world!" ""
.xx "" "let's c" "heck special characters:" ""
.xx "" "let's check special c" "haracters:" ""
.xx "" "let's check spec" "ial characters:" ""
.xx "" "let's chec" "k special characters:" ""
.xx "" "{brac" "kets} for tex" ""
.xx "" "oh, and bac" "k\slash" ""
.xx "" "" "let's check special characters:" ""
.xx "" "let's check specia" "l characters:" ""
.xx "" "and some other" "like %a, b#, c$c" ""
.xx "" "he" "llo world!" ""
.xx "" "maybe a" "lso~or^" ""
.xx "" "" "maybe also~or^" ""
.xx "" "a" "nd some other like %a, b#, c$c" ""
.xx "" "oh, a" "nd back\slash" ""
.xx "" "" "oh, and back\slash" ""
.xx "" "and some" "other like %a, b#, c$c" ""
.xx "" "let's check special cha" "racters:" ""
.xx "" "{b" "rackets} for tex" ""
.xx "" "and some othe" "r like %a, b#, c$c" ""
.xx "" """quotes"", for" "roff" ""
.xx "" "let's check special characte" "rs:" ""
.xx "" """quote" "s"", for roff" ""
.xx "" "oh, and back\sla" "sh" ""
.xx "" "oh, and back\" "slash" ""
.xx "" "and" "some other like %a, b#, c$c" ""
.xx "" "let's check" "special characters:" ""
.xx "" "let's check special charac" "ters:" ""
.xx "" "{brackets} for" "tex" ""
.xx "" "le" "t's check special characters:" ""
.xx "" "{bracke" "ts} for tex" ""
.xx "" "hello" "world!" ""
.xx "" "{brackets} for te" "x" ""
.xx "" "ma" "ybe also~or^" ""
.xx "" "" "{brackets} for tex" ""

View file

@ -0,0 +1,24 @@
.xx "" "" """quotes"", for roff" ""
.xx "" "and some other like" "%a, b#, c$c" ""
.xx "" "maybe" "also~or^" ""
.xx "%a, b#, c$c" "" "and some other like" ""
.xx "" "oh," "and back\slash" ""
.xx "" "some other like %a," "b#, c$c" "and"
.xx "" "oh, and" "back\slash" ""
.xx "" "other like %a, b#," "c$c" "and some"
.xx "" "let's check special" "characters:" ""
.xx "characters:" "let's" "check special" ""
.xx "" """quotes""," "for roff" ""
.xx "" "{brackets}" "for tex" ""
.xx "" "" "hello world!" ""
.xx "characters:" "" "let's check special" ""
.xx "" "and some other" "like %a, b#, c$c" ""
.xx "" "" "maybe also~or^" ""
.xx "" "" "oh, and back\slash" ""
.xx "" "and some" "other like %a, b#, c$c" ""
.xx "" """quotes"", for" "roff" ""
.xx "b#, c$c" "and" "some other like %a," ""
.xx "" "let's check" "special characters:" ""
.xx "" "{brackets} for" "tex" ""
.xx "" "hello" "world!" ""
.xx "" "" "{brackets} for tex" ""

View file

@ -0,0 +1,24 @@
.xx "" "" """quotes"", for roff" ""
.xx "" "and some other like" "%a, b#, c$c" ""
.xx "" "maybe" "also~or^" ""
.xx "" "" "and some other like %a, b#, c$c" ""
.xx "" "oh," "and back\slash" ""
.xx "" "and some other like %a," "b#, c$c" ""
.xx "" "oh, and" "back\slash" ""
.xx "" "and some other like %a, b#," "c$c" ""
.xx "" "let's check special" "characters:" ""
.xx "" "let's" "check special characters:" ""
.xx "" """quotes""," "for roff" ""
.xx "" "{brackets}" "for tex" ""
.xx "" "" "hello world!" ""
.xx "" "" "let's check special characters:" ""
.xx "" "and some other" "like %a, b#, c$c" ""
.xx "" "" "maybe also~or^" ""
.xx "" "" "oh, and back\slash" ""
.xx "" "and some" "other like %a, b#, c$c" ""
.xx "" """quotes"", for" "roff" ""
.xx "" "and" "some other like %a, b#, c$c" ""
.xx "" "let's check" "special characters:" ""
.xx "" "{brackets} for" "tex" ""
.xx "" "hello" "world!" ""
.xx "" "" "{brackets} for tex" ""