Skip to content

Commit

Permalink
Add support for IPAddress and IPEndpoint arguments (#1735)
Browse files Browse the repository at this point in the history
* Add support of IPAddress and IPEndpoint arguments

* IPEndPoint.TryParse isn't supported until .Net 7

* TryParse should work from .Net Core >= 3.1

* Add missing [Fact] attributes

* Remove nullable IPAddress/IPEndPoint tests
  • Loading branch information
RobThree authored May 9, 2022
1 parent 55dbf39 commit 1ac7dfd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/System.CommandLine.Tests/Binding/TypeConversionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using FluentAssertions;
using System.Linq;
using Xunit;
using System.Net;

namespace System.CommandLine.Tests.Binding
{
Expand Down Expand Up @@ -708,7 +709,29 @@ public void Values_can_be_correctly_converted_to_nullable_sbyte_without_the_pars

value.Should().Be(123);
}


[Fact]
public void Values_can_be_correctly_converted_to_ipaddress_without_the_parser_specifying_a_custom_converter()
{
var option = new Option<IPAddress>("-us");

var value = option.Parse("-us 1.2.3.4").GetValueForOption(option);

value.Should().Be(IPAddress.Parse("1.2.3.4"));
}

#if NETCOREAPP3_0_OR_GREATER
[Fact]
public void Values_can_be_correctly_converted_to_ipendpoint_without_the_parser_specifying_a_custom_converter()
{
var option = new Option<IPEndPoint>("-us");

var value = option.Parse("-us 1.2.3.4:56").GetValueForOption(option);

value.Should().Be(IPEndPoint.Parse("1.2.3.4:56"));
}
#endif

[Fact]
public void Values_can_be_correctly_converted_to_byte_without_the_parser_specifying_a_custom_converter()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Generic;
using System.IO;
using System.Net;

namespace System.CommandLine.Binding;

Expand Down Expand Up @@ -154,6 +155,32 @@ internal static partial class ArgumentConverter
return false;
},

[typeof(IPAddress)] = (string token, out object? value) =>
{
if (IPAddress.TryParse(token, out var ip))
{
value = ip;
return true;
}

value = default;
return false;
},

#if NETCOREAPP3_0_OR_GREATER
[typeof(IPEndPoint)] = (string token, out object? value) =>
{
if (IPEndPoint.TryParse(token, out var ipendpoint))
{
value = ipendpoint;
return true;
}

value = default;
return false;
},
#endif

[typeof(long)] = (string token, out object? value) =>
{
if (long.TryParse(token, out var longValue))
Expand Down

0 comments on commit 1ac7dfd

Please sign in to comment.