normalize_ip_for_uri: allow to give an array of IP addresses

Allow to give an array of IP addresses to normalize_ip_for_url function.
Each IP in the list will be normalized like it would be for a string.

Change-Id: I8d361ce9cfcfe6a3f8592b2b7991971a3c748c75
Co-Authored-By: Athlan-Guyot sofer <sathlang@redhat.com>
This commit is contained in:
Emilien Macchi 2016-09-20 02:00:07 -04:00 committed by Sofer Athlan-Guyot
parent 7c889eccbe
commit 435c50fe88
3 changed files with 27 additions and 15 deletions

View File

@ -3,7 +3,6 @@ require 'ipaddr'
module Puppet::Parser::Functions
newfunction(:normalize_ip_for_uri,
:type => :rvalue,
:arity => 1,
:doc => <<-EOD
Add brackets if the argument is an IPv6 address.
Returns the argument untouched otherwise.
@ -13,19 +12,26 @@ module Puppet::Parser::Functions
and port 8080. This code will change it to
[2001::1:8080] as it's a valid ip address. This
shouldn't be an issue in most cases.
If an array is given, each member will be normalized to
a valid IPv6 address with brackets when needed.
EOD
) do |args|
ip = args[0]
begin
if IPAddr.new(ip).ipv6?
unless ip.match(/\[.+\]/)
Puppet.debug("IP #{ip} is changed to [#{ip}]")
ip = "[#{ip}]"
) do |args|
result = []
args = args[0] if args[0].kind_of?(Array)
args.each do |ip|
begin
if IPAddr.new(ip).ipv6?
unless ip.match(/\[.+\]/)
Puppet.debug("IP #{ip} is changed to [#{ip}]")
ip = "[#{ip}]"
end
end
rescue ArgumentError
# ignore it
end
rescue ArgumentError => e
# ignore it
result << ip
end
return ip
return result[0] if args.size == 1
result
end
end

View File

@ -0,0 +1,4 @@
---
features:
- Allow to give an array of IP addresses to normalize_ip_for_uri and normalize
each IP in the list.

View File

@ -6,8 +6,10 @@ describe 'normalize_ip_for_uri' do
it { should run.with_params('127.0.0.1').and_return('127.0.0.1')}
it { should run.with_params('::1').and_return('[::1]')}
it { should run.with_params('[2001::01]').and_return('[2001::01]')}
it do
is_expected.to run.with_params('one', 'two')
.and_raise_error(ArgumentError, /Wrong number of arguments/)
end
# You're not forced to pass an array, a list of argument will do.
it { should run.with_params('::1','::2').and_return(['[::1]','[::2]'])}
it { should run.with_params(['::1','::2']).and_return(['[::1]','[::2]'])}
it { should run.with_params(['::1','[::2]','::3']).and_return(['[::1]','[::2]','[::3]'])}
it { should run.with_params(['192.168.0.1','[::2]']).and_return(['192.168.0.1','[::2]'])}
it { should run.with_params(['192.168.0.1','::2']).and_return(['192.168.0.1','[::2]'])}
end