Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / validate_ipv4_address.rb
1 #
2 # validate_ipv4_address.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:validate_ipv4_address, :doc => <<-DOC
6     @summary
7       Validate that all values passed are valid IPv4 addresses.
8       Fail compilation if any value fails this check.
9
10     @return
11       passes when the given values are valid IPv4 addresses or raise an error when they are not and fails compilation
12
13     @example **Usage**
14       The following values will pass:
15
16         $my_ip = "1.2.3.4"
17         validate_ipv4_address($my_ip)
18         validate_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip)
19
20       The following values will fail, causing compilation to abort:
21
22         $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ]
23         validate_ipv4_address($some_array)
24     DOC
25              ) do |args|
26
27     function_deprecation([:validate_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function,
28                             with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.'])
29
30     require 'ipaddr'
31     rescuable_exceptions = [ArgumentError]
32
33     if defined?(IPAddr::InvalidAddressError)
34       rescuable_exceptions << IPAddr::InvalidAddressError
35     end
36
37     if args.empty?
38       raise Puppet::ParseError, "validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)"
39     end
40
41     args.each do |arg|
42       unless arg.is_a?(String)
43         raise Puppet::ParseError, "#{arg.inspect} is not a string."
44       end
45
46       begin
47         unless IPAddr.new(arg).ipv4?
48           raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address."
49         end
50       rescue *rescuable_exceptions
51         raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address."
52       end
53     end
54   end
55 end