From 9e24e452a555542efe2498efa355b0ae63831d5d Mon Sep 17 00:00:00 2001 From: nibon7 Date: Fri, 29 Jul 2022 19:41:28 +0800 Subject: [PATCH] Fix touch panics when using invalid timestamp (#6181) Signed-off-by: nibon7 --- crates/nu-command/src/filesystem/touch.rs | 14 ++++++++++++-- crates/nu-command/tests/commands/touch.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/nu-command/src/filesystem/touch.rs b/crates/nu-command/src/filesystem/touch.rs index 485c2bc5f..1806c6506 100644 --- a/crates/nu-command/src/filesystem/touch.rs +++ b/crates/nu-command/src/filesystem/touch.rs @@ -140,14 +140,24 @@ impl Command for Touch { 10 => Some(AddYear::Full), 12 => Some(AddYear::FirstDigits), 14 => None, - _ => unreachable!(), // This should never happen as the check above should catch it + _ => { + return Err(ShellError::UnsupportedInput( + "input has an invalid timestamp".to_string(), + span, + )) + } } } else { match size { 8 => Some(AddYear::Full), 10 => Some(AddYear::FirstDigits), 12 => None, - _ => unreachable!(), // This should never happen as the check above should catch it + _ => { + return Err(ShellError::UnsupportedInput( + "input has an invalid timestamp".to_string(), + span, + )) + } } }; diff --git a/crates/nu-command/tests/commands/touch.rs b/crates/nu-command/tests/commands/touch.rs index 66865c3f5..04c2518eb 100644 --- a/crates/nu-command/tests/commands/touch.rs +++ b/crates/nu-command/tests/commands/touch.rs @@ -766,3 +766,20 @@ fn not_create_file_if_it_not_exists() { assert!(!path.exists()); }) } + +#[test] +fn test_invalid_timestamp() { + Playground::setup("test_invalid_timestamp", |dirs, _sandbox| { + let outcome = nu!( + cwd: dirs.test(), + r#"touch -t 20220729. file.txt"# + ); + assert!(outcome.err.contains("input has an invalid timestamp")); + + let outcome = nu!( + cwd: dirs.test(), + r#"touch -t 20220729120099 file.txt"# + ); + assert!(outcome.err.contains("input has an invalid timestamp")); + }) +}