From 372d408431a3c0001cbe9e8e247a8e1561dc2e89 Mon Sep 17 00:00:00 2001 From: Gabriel DeBacker <6741868+GabeDeBacker@users.noreply.github.com> Date: Fri, 22 Apr 2022 14:02:51 -0400 Subject: [PATCH] Add TimeSpan string converter (#1718) --- .../Binding/TypeConversionTests.cs | 22 +++++++++++++++++++ .../ArgumentConverter.StringConverters.cs | 12 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs b/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs index 0e15ae1af4..8b64bbd00e 100644 --- a/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs +++ b/src/System.CommandLine.Tests/Binding/TypeConversionTests.cs @@ -568,6 +568,28 @@ public void Values_can_be_correctly_converted_to_nullable_Guid_without_the_parse value.Should().Be(Guid.Parse(guidString)); } + [Fact] + public void Values_can_be_correctly_converted_to_TimeSpan_without_the_parser_specifying_a_custom_converter() + { + var timeSpanString = "30"; + var option = new Option("-x"); + + var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option); + + value.Should().Be(TimeSpan.Parse(timeSpanString)); + } + + [Fact] + public void Values_can_be_correctly_converted_to_nullable_TimeSpan_without_the_parser_specifying_a_custom_converter() + { + var timeSpanString = "30"; + var option = new Option("-x"); + + var value = option.Parse($"-x {timeSpanString}").GetValueForOption(option); + + value.Should().Be(TimeSpan.Parse(timeSpanString)); + } + [Fact] public void Values_can_be_correctly_converted_to_Uri_without_the_parser_specifying_a_custom_converter() { diff --git a/src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs b/src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs index 24b2b8fb7b..c4e56bad5e 100644 --- a/src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs +++ b/src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs @@ -255,5 +255,17 @@ internal static partial class ArgumentConverter value = default; return false; }, + + [typeof(TimeSpan)] = (string input, out object? value) => + { + if (TimeSpan.TryParse(input, out var timeSpan)) + { + value = timeSpan; + return true; + } + + value = default; + return false; + }, }; } \ No newline at end of file