ls: when facing an invalid utf-8, don't panic

Fails with
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: "invalid-\xE0-"', src/uu/ls/src/ls.rs:1932:53
```
This commit is contained in:
Sylvestre Ledru 2023-05-14 21:47:58 +02:00
parent 49c16a2f11
commit 3e7594632b
2 changed files with 23 additions and 1 deletions

View file

@ -1997,7 +1997,15 @@ fn should_display(entry: &DirEntry, config: &Config) -> bool {
require_literal_separator: false,
case_sensitive: true,
};
let file_name = entry.file_name().into_string().unwrap();
let file_name = entry.file_name();
// If the decoding fails, still show an incorrect rendering
let file_name = match file_name.to_str() {
Some(s) => s.to_string(),
None => {
let file_name_bytes = file_name.to_string_lossy();
file_name_bytes.into_owned()
}
};
!config
.ignore_patterns
.iter()

View file

@ -7,6 +7,10 @@ use crate::common::util::TestScenario;
use nix::unistd::{close, dup};
use regex::Regex;
use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::ffi::OsStr;
#[cfg(target_os = "linux")]
use std::os::unix::ffi::OsStrExt;
#[cfg(all(unix, feature = "chmod"))]
use std::os::unix::io::IntoRawFd;
use std::path::Path;
@ -3434,3 +3438,13 @@ fn test_device_number() {
.succeeds()
.stdout_contains(major_minor_str);
}
#[test]
#[cfg(target_os = "linux")]
fn test_invalid_utf8() {
let (at, mut ucmd) = at_and_ucmd!();
let filename = OsStr::from_bytes(b"-\xE0-foo");
at.touch(filename);
ucmd.succeeds();
}