diff --git a/lib/puppet/functions/extlib/compare_ip.rb b/lib/puppet/functions/extlib/compare_ip.rb new file mode 100644 index 0000000..efefdce --- /dev/null +++ b/lib/puppet/functions/extlib/compare_ip.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require 'ipaddr' + +# A function that compares two IP addresses. To be used with the built-in sort() +# function. +Puppet::Functions.create_function(:'extlib::compare_ip') do + # @param a First value + # @param b Second value + # @return -1, 0 or 1 if first value is lesser, equal or greater than second value + # @example Sorting the array of IP addresses + # $ip_addresses = ['10.1.1.1', '10.10.1.1', '10.2.1.1'] + # $ip_addresses.sort |$a, $b| { extlib::compare_ip($a, $b) } + dispatch :compare_ip do + param 'String[1]', :left + param 'String[1]', :right + return_type 'Integer[-1,1]' + end + + def compare_ip(left, right) + IPAddr.new(left).to_i <=> IPAddr.new(right).to_i + end +end diff --git a/spec/functions/extlib/compare_ip_spec.rb b/spec/functions/extlib/compare_ip_spec.rb new file mode 100644 index 0000000..8a288f7 --- /dev/null +++ b/spec/functions/extlib/compare_ip_spec.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require 'spec_helper' + +describe 'extlib::compare_ip' do + it 'exists' do + is_expected.not_to be_nil + end + + it { is_expected.to run.with_params('10.1.1.1', '10.2.1.1').and_return(-1) } + it { is_expected.to run.with_params('10.2.1.1', '10.2.1.1').and_return(0) } + it { is_expected.to run.with_params('10.10.1.1', '10.2.1.1').and_return(1) } + + it { is_expected.to run.with_params('fe80::1', 'fe80::2').and_return(-1) } + it { is_expected.to run.with_params('fe80::2', 'fe80::2').and_return(0) } + it { is_expected.to run.with_params('fe80::10', 'fe80::2').and_return(1) } + + it { is_expected.to run.with_params('0::ffff:fffe', '255.255.255.255').and_return(-1) } + it { is_expected.to run.with_params('0::ffff:ffff', '255.255.255.255').and_return(0) } + it { is_expected.to run.with_params('0::1:0:0', '255.255.255.255').and_return(1) } +end