Skip to content

Commit

Permalink
tr: properly determine trailing backslash
Browse files Browse the repository at this point in the history
Fixes #6729.
  • Loading branch information
BenWiederhake committed Sep 24, 2024
1 parent 165bbc2 commit a8b9e04
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
24 changes: 7 additions & 17 deletions src/uu/tr/src/tr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,23 +99,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {

if let Some(first) = sets.first() {
let slice = os_str_as_bytes(first)?;

let mut iter = slice.iter();

if let Some(b'\\') = iter.next_back() {
match iter.next_back() {
Some(b'\\') => {
// The trailing backslash has a backslash preceding it, so it is properly escaped
}
_ => {
// The trailing backslash has a non-backslash character before it OR is the only character in the
// string, so the warning applies
show!(USimpleError::new(
0,
"warning: an unescaped backslash at end of string is not portable"
));
}
}
let trailing_backslashes = slice.iter().rev().take_while(|&&c| c == b'\\').count();
if trailing_backslashes % 2 == 1 {
// The trailing backslash has a non-backslash character before it.
show!(USimpleError::new(
0,
"warning: an unescaped backslash at end of string is not portable"
));
}
}

Expand Down
24 changes: 23 additions & 1 deletion tests/by-util/test_tr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1456,15 +1456,37 @@ fn test_unescaped_backslash_warning_false_positive() {
.pipe_in(r"a\b\c\")
.succeeds()
.stdout_only("abc");
new_ucmd!()
.args(&["-d", r"\\\\"])
.pipe_in(r"a\b\c\")
.succeeds()
.stdout_only("abc");
new_ucmd!()
.args(&["-d", r"\\\\\\"])
.pipe_in(r"a\b\c\")
.succeeds()
.stdout_only("abc");
}

#[test]
#[cfg(unix)]
fn test_trailing_backslash_is_only_input_character() {
fn test_trailing_backslash() {
new_ucmd!()
.args(&["-d", r"\"])
.pipe_in(r"a\b\c\")
.succeeds()
.stderr_is("tr: warning: an unescaped backslash at end of string is not portable\n")
.stdout_is("abc");
new_ucmd!()
.args(&["-d", r"\\\"])
.pipe_in(r"a\b\c\")
.succeeds()
.stderr_is("tr: warning: an unescaped backslash at end of string is not portable\n")
.stdout_is("abc");
new_ucmd!()
.args(&["-d", r"\\\\\"])
.pipe_in(r"a\b\c\")
.succeeds()
.stderr_is("tr: warning: an unescaped backslash at end of string is not portable\n")
.stdout_is("abc");
}

0 comments on commit a8b9e04

Please sign in to comment.