Commit 1042df79 authored by James T. Lee's avatar James T. Lee
Browse files

Move puppet libraries into module for Puppet 7 compat

parent d8c34007
# frozen_string_literal: true
#
# basename.rb
#
module Puppet::Parser::Functions
newfunction(:basename, type: :rvalue, doc: <<-DOC
@summary
Strips directory (and optional suffix) from a filename
@return [String] The stripped filename
DOC
) do |arguments|
raise(Puppet::ParseError, 'basename(): No arguments given') if arguments.empty?
raise(Puppet::ParseError, "basename(): Too many arguments given (#{arguments.size})") if arguments.size > 2
raise(Puppet::ParseError, 'basename(): Requires string as first argument') unless arguments[0].is_a?(String)
rv = File.basename(arguments[0]) if arguments.size == 1
if arguments.size == 2
raise(Puppet::ParseError, 'basename(): Requires string as second argument') unless arguments[1].is_a?(String)
rv = File.basename(arguments[0], arguments[1])
end
return rv
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# bool2num.rb
#
module Puppet::Parser::Functions
newfunction(:bool2num, type: :rvalue, doc: <<-DOC
@summary
Converts a boolean to a number.
Converts the values:
```
false, f, 0, n, and no to 0
true, t, 1, y, and yes to 1
```
Requires a single boolean or string as an input.
> *Note:*
since Puppet 5.0.0 it is possible to create new data types for almost any
datatype using the type system and the built-in
[`Numeric.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-numeric),
[`Integer.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-integer), and
[`Float.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-float)
function are used to convert to numeric values.
```
notice(Integer(false)) # Notices 0
notice(Float(true)) # Notices 1.0
```
@return [Integer] The converted value as a number
DOC
) do |arguments|
raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
value = function_str2bool([arguments[0]])
# We have real boolean values as well ...
result = value ? 1 : 0
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# bool2str.rb
#
module Puppet::Parser::Functions
newfunction(:bool2str, type: :rvalue, doc: <<-DOC
@summary
Converts a boolean to a string using optionally supplied arguments.
The optional second and third arguments represent what true and false will be
converted to respectively. If only one argument is given, it will be
converted from a boolean to a string containing 'true' or 'false'.
@return
The converted value to string of the given Boolean
**Examples of usage**
```
bool2str(true) => 'true'
bool2str(true, 'yes', 'no') => 'yes'
bool2str(false, 't', 'f') => 'f'
```
Requires a single boolean as an input.
> *Note:*
since Puppet 5.0.0 it is possible to create new data types for almost any
datatype using the type system and the built-in
[`String.new`](https://puppet.com/docs/puppet/latest/function.html#boolean-to-string)
function is used to convert to String with many different format options.
```
notice(String(false)) # Notices 'false'
notice(String(true)) # Notices 'true'
notice(String(false, '%y')) # Notices 'yes'
notice(String(true, '%y')) # Notices 'no'
```
DOC
) do |arguments|
unless arguments.size == 1 || arguments.size == 3
raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)")
end
value = arguments[0]
true_string = arguments[1] || 'true'
false_string = arguments[2] || 'false'
klass = value.class
# We can have either true or false, and nothing else
unless [FalseClass, TrueClass].include?(klass)
raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with')
end
unless [true_string, false_string].all? { |x| x.is_a?(String) }
raise(Puppet::ParseError, 'bool2str(): Requires strings to convert to')
end
return value ? true_string : false_string
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# camelcase.rb
# 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.
#
module Puppet::Parser::Functions
newfunction(:camelcase, type: :rvalue, doc: <<-DOC
@summary
**Deprecated** Converts the case of a string or all strings in an array to camel case.
> *Note:*
**Deprecated** from Puppet 6.0.0, this function has been replaced with
a built-in [`camelcase`](https://puppet.com/docs/puppet/latest/function.html#camelcase)
function.
@return [String] The converted String, if it was a String that was given
@return [Array[String]] The converted Array, if it was a Array that was given
DOC
) do |arguments|
raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
value = arguments[0]
klass = value.class
unless [Array, String].include?(klass)
raise(Puppet::ParseError, 'camelcase(): Requires either array or string to work with')
end
result = if value.is_a?(Array)
# Numbers in Puppet are often string-encoded which is troublesome ...
value.map { |i| i.is_a?(String) ? i.split('_').map { |e| e.capitalize }.join : i }
else
value.split('_').map { |e| e.capitalize }.join
end
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# capitalize.rb
# 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.
#
module Puppet::Parser::Functions
newfunction(:capitalize, type: :rvalue, doc: <<-DOC
@summary
**Deprecated** Capitalizes the first letter of a string or array of strings.
Requires either a single string or an array as an input.
> *Note:*
**Deprecated** from Puppet 6.0.0, yhis function has been replaced with a
built-in [`capitalize`](https://puppet.com/docs/puppet/latest/function.html#capitalize)
function.
@return [String] The converted String, if it was a String that was given
@return [Array[String]] The converted Array, if it was a Array that was given
DOC
) do |arguments|
raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
value = arguments[0]
unless value.is_a?(Array) || value.is_a?(String)
raise(Puppet::ParseError, 'capitalize(): Requires either array or string to work with')
end
result = if value.is_a?(Array)
# Numbers in Puppet are often string-encoded which is troublesome ...
value.map { |i| i.is_a?(String) ? i.capitalize : i }
else
value.capitalize
end
return result
end
end
# frozen_string_literal: true
#
# ceiling.rb
#
module Puppet::Parser::Functions
newfunction(:ceiling, type: :rvalue, doc: <<-DOC
@summary
**Deprecated** Returns the smallest integer greater or equal to the argument.
Takes a single numeric value as an argument.
> *Note:*
**Deprecated** from Puppet 6.0.0, this function has been replaced with a
built-in [`ceiling`](https://puppet.com/docs/puppet/latest/function.html#ceiling) function.
@return [Integer] The rounded value
DOC
) do |arguments|
raise(Puppet::ParseError, "ceiling(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1
begin
arg = Float(arguments[0])
rescue TypeError, ArgumentError => _e
raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arguments[0]} for Numeric)")
end
raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false
arg.ceil
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# chomp.rb
#
module Puppet::Parser::Functions
newfunction(:chomp, type: :rvalue, doc: <<-DOC
@summary
**Deprecated** Removes the record separator from the end of a string or an array of strings.
For example `hello\n` becomes `hello`.
Requires a single string or array as an input.
> *Note:*
**Deprecated** from Puppet 6.0.0, this function has been replaced with a
built-in [`chomp`](https://puppet.com/docs/puppet/latest/function.html#chomp) function.
@return [String] The converted String, if it was a String that was given
@return [Array[String]] The converted Array, if it was a Array that was given
DOC
) do |arguments|
raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
value = arguments[0]
unless value.is_a?(Array) || value.is_a?(String)
raise(Puppet::ParseError, 'chomp(): Requires either array or string to work with')
end
result = if value.is_a?(Array)
# Numbers in Puppet are often string-encoded which is troublesome ...
value.map { |i| i.is_a?(String) ? i.chomp : i }
else
value.chomp
end
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# chop.rb
#
module Puppet::Parser::Functions
newfunction(:chop, type: :rvalue, doc: <<-DOC
@summary
**Deprecated** Returns a new string with the last character removed.
If the string ends with `\r\n`, both characters are removed. Applying
chop to an empty string returns an empty string. If you wish to merely
remove record separators then you should use the `chomp` function.
Requires a string or array of strings as input.
> *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a
built-in [`chop`](https://puppet.com/docs/puppet/latest/function.html#chop) function.
@return [String] The given String, sans the last character.
DOC
) do |arguments|
raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
value = arguments[0]
unless value.is_a?(Array) || value.is_a?(String)
raise(Puppet::ParseError, 'chop(): Requires either an array or string to work with')
end
result = if value.is_a?(Array)
# Numbers in Puppet are often string-encoded which is troublesome ...
value.map { |i| i.is_a?(String) ? i.chop : i }
else
value.chop
end
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# clamp.rb
#
module Puppet::Parser::Functions
newfunction(:clamp, type: :rvalue, arity: -2, doc: <<-DOC
@summary
Keeps value within the range [Min, X, Max] by sort based on integer value
(parameter order doesn't matter).
Strings are converted and compared numerically. Arrays of values are flattened
into a list for further handling.
@example Example usage
clamp('24', [575, 187])` returns 187.
clamp(16, 88, 661)` returns 88.
clamp([4, 3, '99'])` returns 4.
> *Note:*
From Puppet 6.0.0 this can be done with only core Puppet like this:
`[$minval, $maxval, $value_to_clamp].sort[1]`
@return [Array[Integer]] The sorted Array
DOC
) do |args|
args.flatten!
raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3
# check values out
args.each do |value|
case [value.class]
when [String]
raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless %r{^\d+$}.match?(value)
when [Hash]
raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})")
end
end
# convert to numeric each element
# then sort them and get a middle value
args.map { |n| n.to_i }.sort[1]
end
end
# frozen_string_literal: true
#
# concat.rb
#
module Puppet::Parser::Functions
newfunction(:concat, type: :rvalue, doc: <<-DOC
@summary
Appends the contents of multiple arrays into array 1.
@example Example usage
concat(['1','2','3'],'4') returns ['1','2','3','4']
concat(['1','2','3'],'4',['5','6','7']) returns ['1','2','3','4','5','6','7']
> *Note:*
Since Puppet 4.0, you can use the `+`` operator for concatenation of arrays and
merge of hashes, and the `<<`` operator for appending:
`['1','2','3'] + ['4','5','6'] + ['7','8','9']` returns `['1','2','3','4','5','6','7','8','9']`
`[1, 2, 3] << 4` returns `[1, 2, 3, 4]`
`[1, 2, 3] << [4, 5]` returns `[1, 2, 3, [4, 5]]`
@return [Array] The single concatenated array
DOC
) do |arguments|
# Check that more than 2 arguments have been given ...
raise(Puppet::ParseError, "concat(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2
a = arguments[0]
# Check that the first parameter is an array
unless a.is_a?(Array)
raise(Puppet::ParseError, 'concat(): Requires array to work with')
end
result = a
arguments.shift
arguments.each do |x|
result += (x.is_a?(Array) ? x : [x])
end
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# convert_base.rb
#
module Puppet::Parser::Functions
newfunction(:convert_base, type: :rvalue, arity: 2, doc: <<-'DOC') do |args|
@summary
Converts a given integer or base 10 string representing an integer to a
specified base, as a string.
@return
converted value as a string
@example Example usage
convert_base(5, 2)` results in: `'101'`
convert_base('254', '16')` results in: `'fe'`
> *Note:*
Since Puppet 4.5.0 this can be done with the built-in
[`String.new`](https://puppet.com/docs/puppet/latest/function.html#integer-to-string)
function and its many formatting options:
`$binary_repr = String(5, '%b')` return `"101"`
`$hex_repr = String(254, "%x")` return `"fe"`
`$hex_repr = String(254, "%#x")` return `"0xfe"`
@return [String] The converted value as a String
DOC
raise Puppet::ParseError, 'convert_base(): First argument must be either a string or an integer' unless args[0].is_a?(Integer) || args[0].is_a?(String)
raise Puppet::ParseError, 'convert_base(): Second argument must be either a string or an integer' unless args[1].is_a?(Integer) || args[1].is_a?(String)
if args[0].is_a?(String)
raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless %r{^[0-9]+$}.match?(args[0])
end
if args[1].is_a?(String)
raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless %r{^[0-9]+$}.match?(args[1])
end
number_to_convert = args[0]
new_base = args[1]
number_to_convert = number_to_convert.to_i
new_base = new_base.to_i
raise Puppet::ParseError, 'convert_base(): base must be at least 2 and must not be greater than 36' unless new_base >= 2 && new_base <= 36
return number_to_convert.to_s(new_base)
end
end
# frozen_string_literal: true
#
# count.rb
#
module Puppet::Parser::Functions
newfunction(:count, type: :rvalue, arity: -2, doc: <<-DOC
@summary
Counts the number of elements in array.
Takes an array as first argument and an optional second argument. Counts the number of elements in array that is equal to the second argument.
If called with only an array, it counts the number of elements that are not nil/undef/empty-string.
> *Note:*
equality is tested with a Ruby method and it is therefore subject to what Ruby considers
to be equal. For strings this means that equality is case sensitive.
In Puppet core, counting can be done in general by using a combination of the core functions
filter() (since Puppet 4.0.0) and length() (since Puppet 5.5.0, before that in stdlib).
Example below shows counting values that are not undef.
```notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length)```
Would notice the value 2.
@return [Integer] The amount of elements counted within the array
DOC
) do |args|
if args.size > 2
raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.")
end
collection, item = args
if item
collection.count item
else
collection.count { |obj| !obj.nil? && obj != :undef && obj != '' }
end
end
end
# frozen_string_literal: true
#
# deep_merge.rb
#
module Puppet::Parser::Functions
newfunction(:deep_merge, type: :rvalue, doc: <<-'DOC') do |args|
@summary
Recursively merges two or more hashes together and returns the resulting hash.
@example Example usage
$hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
$hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
$merged_hash = deep_merge($hash1, $hash2)
The resulting hash is equivalent to:
$merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
When there is a duplicate key that is a hash, they are recursively merged.
When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."
@return [Hash] The merged hash
DOC
if args.length < 2
raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)"
end
deep_merge = proc do |hash1, hash2|
hash1.merge(hash2) do |_key, old_value, new_value|
if old_value.is_a?(Hash) && new_value.is_a?(Hash)
deep_merge.call(old_value, new_value)
else
new_value
end
end
end
result = {}
args.each do |arg|
next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef
# If the argument was not a hash, skip it.
unless arg.is_a?(Hash)
raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
end
result = deep_merge.call(result, arg)
end
return(result)
end
end
# frozen_string_literal: true
# Test whether a given class or definition is defined
require 'puppet/parser/functions'
Puppet::Parser::Functions.newfunction(:defined_with_params,
type: :rvalue,
doc: <<-DOC,
@summary
Takes a resource reference and an optional hash of attributes.
Returns `true` if a resource with the specified attributes has already been added
to the catalog, and `false` otherwise.
```
user { 'dan':
ensure => present,
}
if ! defined_with_params(User[dan], {'ensure' => 'present' }) {
user { 'dan': ensure => present, }
}
```
@return [Boolean]
returns `true` or `false`
DOC
) do |vals|
reference, params = vals
raise(ArgumentError, 'Must specify a reference') unless reference
if !params || params == ''
params = {}
end
ret = false
if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0
# Workaround for PE-20308
if reference.is_a?(String)
type_name, title = Puppet::Resource.type_and_title(reference, nil)
type = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type_or_class(find_global_scope, type_name.downcase)
elsif reference.is_a?(Puppet::Resource)
type = reference.type
title = reference.title
else
raise(ArgumentError, "Reference is not understood: '#{reference.class}'")
end
# end workaround
else
type = reference.to_s
title = nil
end
resources = if title.empty?
catalog.resources.select { |r| r.type == type }
else
[findresource(type, title)]
end
resources.compact.each do |res|
# If you call this from within a defined type, it will find itself
next if res.to_s == resource.to_s
matches = params.map do |key, value|
# eql? avoids bugs caused by monkeypatching in puppet
res_is_undef = res[key].eql?(:undef) || res[key].nil?
value_is_undef = value.eql?(:undef) || value.nil?
found_match = (res_is_undef && value_is_undef) || (res[key] == value)
Puppet.debug("Matching resource is #{res}") if found_match
found_match
end
ret = params.empty? || !matches.include?(false)
break if ret
end
Puppet.debug("Resource #{reference} was not determined to be defined") unless ret
ret
end
# frozen_string_literal: true
#
# delete.rb
#
module Puppet::Parser::Functions
newfunction(:delete, type: :rvalue, doc: <<-DOC
@summary
Deletes all instances of a given element from an array, substring from a
string, or key from a hash.
@example Example usage
delete(['a','b','c','b'], 'b')
Would return: ['a','c']
delete({'a'=>1,'b'=>2,'c'=>3}, 'b')
Would return: {'a'=>1,'c'=>3}
delete({'a'=>1,'b'=>2,'c'=>3}, ['b','c'])
Would return: {'a'=>1}
delete('abracadabra', 'bra')
Would return: 'acada'
['a', 'b', 'c', 'b'] - 'b'
Would return: ['a', 'c']
{'a'=>1,'b'=>2,'c'=>3} - ['b','c'])
Would return: {'a' => '1'}
'abracadabra'.regsubst(/bra/, '', 'G')
Would return: 'acada'
> *Note:*
From Puppet 4.0.0 the minus (-) operator deletes values from arrays and keys from a hash
`{'a'=>1,'b'=>2,'c'=>3} - ['b','c'])`
>
A global delete from a string can be performed with the
[`regsubst`](https://puppet.com/docs/puppet/latest/function.html#regsubst) function:
`'abracadabra'.regsubst(/bra/, '', 'G')`
In general, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter)
function can filter out entries from arrays and hashes based on keys and/or values.
@return [String] The filtered String, if one was given.
@return [Hash] The filtered Hash, if one was given.
@return [Array] The filtered Array, if one was given.
DOC
) do |arguments|
raise(Puppet::ParseError, "delete(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2
collection = arguments[0].dup
Array(arguments[1]).each do |item|
case collection
when Array, Hash
collection.delete item
when String
collection.gsub! item, ''
else
raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.")
end
end
collection
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# delete_at.rb
#
module Puppet::Parser::Functions
newfunction(:delete_at, type: :rvalue, doc: <<-DOC) do |arguments|
@summary
Deletes a determined indexed value from an array.
For example
```delete_at(['a','b','c'], 1)```
Would return: `['a','c']`
> *Note:*
Since Puppet 4 this can be done in general with the built-in
[`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
```['a', 'b', 'c'].filter |$pos, $val | { $pos != 1 }```
Or if a delete is wanted from the beginning or end of the array, by using the slice operator [ ]:
```
$array[0, -1] # the same as all the values
$array[2, -1] # all but the first 2 elements
$array[0, -3] # all but the last 2 elements
$array[1, -2] # all but the first and last element
```
@return [Array] The given array, now missing the target value
DOC
raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
array = arguments[0]
unless array.is_a?(Array)
raise(Puppet::ParseError, 'delete_at(): Requires array to work with')
end
index = arguments[1]
if index.is_a?(String) && !index.match(%r{^\d+$})
raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index')
end
result = array.clone
# Numbers in Puppet are often string-encoded which is troublesome ...
index = index.to_i
if index > result.size - 1 # First element is at index 0 is it not?
raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given')
end
result.delete_at(index) # We ignore the element that got deleted ...
return result
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# delete_regex.rb
# 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.
#
module Puppet::Parser::Functions
newfunction(:delete_regex, type: :rvalue, doc: <<-DOC
@summary
Deletes all instances of a given element that match a regular expression
from an array or key from a hash.
Multiple regular expressions are assumed to be matched as an OR.
@example Example usage
delete_regex(['a','b','c','b'], 'b')
Would return: ['a','c']
delete_regex(['a','b','c','b'], ['b', 'c'])
Would return: ['a']
delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b')
Would return: {'a'=>1,'c'=>3}
delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$')
Would return: {'b'=>2,'c'=>3}
> *Note:*
Since Puppet 4 this can be done in general with the built-in
[`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ }
Would return: ['aaa', 'aca']
@return [Array] The given array now missing all targeted values.
DOC
) do |arguments|
raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2
collection = arguments[0].dup
Array(arguments[1]).each do |item|
case collection
when Array, Hash, String
collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) }
else
raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.")
end
end
collection
end
end
# vim: set ts=2 sw=2 et :
# frozen_string_literal: true
#
# delete_undef_values.rb
#
module Puppet::Parser::Functions
newfunction(:delete_undef_values, type: :rvalue, doc: <<-DOC
@summary
Returns a copy of input hash or array with all undefs deleted.
@example Example usage
$hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false})
Would return: {a => 'A', b => '', d => false}
While:
$array = delete_undef_values(['A','',undef,false])
Would return: ['A','',false]
> *Note:*
Since Puppet 4.0.0 the equivalent can be performed with the built-in
[`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
$array.filter |$val| { $val =~ NotUndef }
$hash.filter |$key, $val| { $val =~ NotUndef }
@return [Array] The given array now issing of undefined values.
DOC
) do |args|
raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.empty?
unless args[0].is_a?(Array) || args[0].is_a?(Hash)
raise(Puppet::ParseError, "delete_undef_values(): expected an array or hash, got #{args[0]} type #{args[0].class} ")
end
result = args[0].dup
if result.is_a?(Hash)
result.delete_if { |_, val| val.equal?(:undef) || val.nil? }
elsif result.is_a?(Array)
result.delete :undef
result.delete nil
end
result
end
end
# frozen_string_literal: true
#
# delete_values.rb
#
module Puppet::Parser::Functions
newfunction(:delete_values, type: :rvalue, doc: <<-DOC
@summary
Deletes all instances of a given value from a hash.
@example Example usage
delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')
Would return: {'a'=>'A','c'=>'C','B'=>'D'}
> *Note:*
Since Puppet 4.0.0 the equivalent can be performed with the
built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
$array.filter |$val| { $val != 'B' }
$hash.filter |$key, $val| { $val != 'B' }
@return [Hash] The given hash now missing all instances of the targeted value
DOC
) do |arguments|
raise(Puppet::ParseError, "delete_values(): Wrong number of arguments given (#{arguments.size} of 2)") if arguments.size != 2
hash, item = arguments
unless hash.is_a?(Hash)
raise(TypeError, "delete_values(): First argument must be a Hash. Given an argument of class #{hash.class}.")
end
hash.dup.delete_if { |_key, val| item == val }
end
end
# frozen_string_literal: true
#
# deprecation.rb
#
module Puppet::Parser::Functions
newfunction(:deprecation, doc: <<-DOC
@summary
Function to print deprecation warnings (this is the 3.X version of it).
The uniqueness key - can appear once. The msg is the message text including any positional
information that is formatted by the user/caller of the method.).
@return [String]
return deprecation warnings
DOC
) do |arguments|
raise(Puppet::ParseError, "deprecation: Wrong number of arguments given (#{arguments.size} for 2)") unless arguments.size == 2
key = arguments[0]
message = arguments[1]
if ENV['STDLIB_LOG_DEPRECATIONS'] == 'true'
warning("deprecation. #{key}. #{message}")
end
end
end
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment