Update puppetlabs/stdlib module
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / delete_regex.rb
1 #
2 #  delete_regex.rb
3 #  Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
4 #
5 module Puppet::Parser::Functions
6   newfunction(:delete_regex, :type => :rvalue, :doc => <<-DOC
7     deletes all instances of a given element that match a regular expression
8     from an array or key from a hash. Multiple regular expressions are assumed
9     to be matched as an OR.
10
11     *Examples:*
12
13         delete_regex(['a','b','c','b'], 'b')
14         Would return: ['a','c']
15
16         delete_regex(['a','b','c','b'], ['b', 'c'])
17         Would return: ['a']
18
19         delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b')
20         Would return: {'a'=>1,'c'=>3}
21
22         delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$')
23         Would return: {'b'=>2,'c'=>3}
24
25      Note that since Puppet 4 this can be done in general with the filter function:
26
27         ["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ }
28         # Would return: ['aaa', 'aca']
29
30
31   DOC
32              ) do |arguments|
33
34     raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2
35
36     collection = arguments[0].dup
37     Array(arguments[1]).each do |item|
38       case collection
39       when Array, Hash, String
40         collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) }
41       else
42         raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.")
43       end
44     end
45     collection
46   end
47 end
48
49 # vim: set ts=2 sw=2 et :