Skip to content

Add support for IPAddress and IPEndpoint arguments #1735

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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