feat: initial commit

This commit is contained in:
amy 2025-04-01 17:40:03 +00:00
commit 38f495e3f4
457 changed files with 40577 additions and 0 deletions

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::batch_escape`](#stdlibbatch_escape) instead.
Puppet::Functions.create_function(:batch_escape) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'batch_escape', 'This function is deprecated, please use stdlib::batch_escape instead.', false)
call_function('stdlib::batch_escape', *args)
end
end

View file

@ -0,0 +1,38 @@
# frozen_string_literal: true
# @summary Function to print deprecation warnings, Logs a warning once for a given key.
Puppet::Functions.create_function(:deprecation) do
# @param key
# The uniqueness key. This function logs once for any given key.
# @param message
# Is the message text including any positional information that is formatted by the user/caller of the function.
# @param use_strict_setting
# When `true`, (the default), the function is affected by the puppet setting 'strict', which can be set to :error
# (outputs as an error message), :off (no message / error is displayed) and :warning
# (default, outputs a warning).
dispatch :deprecation do
param 'String', :key
param 'String', :message
optional_param 'Boolean', :use_strict_setting
end
def deprecation(key, message, use_strict_setting = true) # rubocop:disable Style/OptionalBooleanParameter
if defined? Puppet::Pops::PuppetStack.stacktrace
stacktrace = Puppet::Pops::PuppetStack.stacktrace
file = stacktrace[0]
line = stacktrace[1]
message = "#{message} at #{file}:#{line}"
end
# Do nothing if using strict setting and strict is set to `off`
return if use_strict_setting && Puppet.settings[:strict] == :off
# Fail hard if using strict setting and strict is set to `error`
raise("deprecation. #{key}. #{message}") if use_strict_setting && Puppet.settings[:strict] == :error
# Otherwise raise a soft warning
# (unless the STDLIB_LOG_DEPRECATIONS has been set to `false`. This is mainly for use in rspec-puppet testing to suppress noise in logs)
Puppet.deprecation_warning(message, key) unless ENV['STDLIB_LOG_DEPRECATIONS'] == 'false'
nil
end
end

View file

@ -0,0 +1,13 @@
# frozen_string_literal: true
# @summary DEPRECATED. Use the namespaced function [`stdlib::ensure_packages`](#stdlibensure_packages) instead.
Puppet::Functions.create_function(:ensure_packages, Puppet::Functions::InternalFunction) do
dispatch :deprecation_gen do
scope_param
repeated_param 'Any', :args
end
def deprecation_gen(scope, *args)
call_function('deprecation', 'ensure_packages', 'This function is deprecated, please use stdlib::ensure_packages instead.', false)
scope.call_function('stdlib::ensure_packages', args)
end
end

View file

@ -0,0 +1,65 @@
# frozen_string_literal: true
# @summary
# Digs into the facts hash using dot-notation
#
# Supports the use of dot-notation for referring to structured facts. If a fact requested
# does not exist, returns Undef.
#
# @example Example usage:
# fact('osfamily')
# fact('os.architecture')
#
# @example Array indexing:
# fact('mountpoints."/dev".options.1')
#
# @example Fact containing a "." in the name:
# fact('vmware."VRA.version"')
#
Puppet::Functions.create_function(:fact) do
# @param fact_name
# The name of the fact to check
#
# @return
# All information retrieved on the given fact_name
dispatch :fact do
param 'String', :fact_name
end
def to_dot_syntax(array_path)
array_path.map { |string|
string.include?('.') ? %("#{string}") : string
}.join('.')
end
def fact(fact_name)
facts = closure_scope['facts']
# Transform the dot-notation string into an array of paths to walk. Make
# sure to correctly extract double-quoted values containing dots as single
# elements in the path.
path = fact_name.scan(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first }
walked_path = []
path.reduce(facts) do |d, k|
return nil if d.nil? || k.nil?
if d.is_a?(Array)
begin
result = d[Integer(k)]
rescue ArgumentError => e # rubocop:disable Lint/UselessAssignment : Causes errors if assigment is removed.
Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'")
result = nil
end
elsif d.is_a?(Hash)
result = d[k]
else
Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is not a collection; cannot walk to '#{k}'")
result = nil
end
walked_path << k
result
end
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::fqdn_rand_string`](#stdlibfqdn_rand_string) instead.
Puppet::Functions.create_function(:fqdn_rand_string) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'fqdn_rand_string', 'This function is deprecated, please use stdlib::fqdn_rand_string instead.', false)
call_function('stdlib::fqdn_rand_string', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::fqdn_rotate`](#stdlibfqdn_rotate) instead.
Puppet::Functions.create_function(:fqdn_rotate) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'fqdn_rotate', 'This function is deprecated, please use stdlib::fqdn_rotate instead.', false)
call_function('stdlib::fqdn_rotate', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::has_interface_with`](#stdlibhas_interface_with) instead.
Puppet::Functions.create_function(:has_interface_with) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'has_interface_with', 'This function is deprecated, please use stdlib::has_interface_with instead.', false)
call_function('stdlib::has_interface_with', *args)
end
end

View file

@ -0,0 +1,44 @@
# frozen_string_literal: true
# @summary
# Boolean check to determine whether a variable is of a given data type.
# This is equivalent to the `=~` type checks.
#
# @example Example Usage:
# # check a data type
# foo = 3
# $bar = [1,2,3]
# $baz = 'A string!'
#
# if $foo.is_a(Integer) {
# notify { 'foo!': }
# }
# if $bar.is_a(Array) {
# notify { 'bar!': }
# }
# if $baz.is_a(String) {
# notify { 'baz!': }
# }
#
# See the documentation for "The Puppet Type System" for more information about types.
# See the `assert_type()` function for flexible ways to assert the type of a value.
#
Puppet::Functions.create_function(:is_a) do
# @param value
# The value to be checked
#
# @param type
# The expected type
#
# @return [Boolean]
# Return's `true` or `false`.
dispatch :is_a do
param 'Any', :value
param 'Type', :type
end
def is_a(value, type) # rubocop:disable Naming/PredicateName : Used in to many other places to rename at this time, attempting to refactor caused Rubocop to crash.
# See puppet's lib/puppet/pops/evaluator/evaluator_impl.rb eval_MatchExpression
Puppet::Pops::Types::TypeCalculator.instance?(type, value)
end
end

View file

@ -0,0 +1,15 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::merge`](#stdlibmerge) instead.
Puppet::Functions.create_function(:merge) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
optional_block_param 'Variant[Callable[2,2], Callable[3,3]]', :block
end
def deprecation_gen(*args, &block)
call_function('deprecation', 'merge', 'This function is deprecated, please use stdlib::merge instead.', false)
call_function('stdlib::merge', *args, &block)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::os_version_gte`](#stdlibos_version_gte) instead.
Puppet::Functions.create_function(:os_version_gte) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'os_version_gte', 'This function is deprecated, please use stdlib::os_version_gte instead.', false)
call_function('stdlib::os_version_gte', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::parsehocon`](#stdlibparsehocon) instead.
Puppet::Functions.create_function(:parsehocon) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'parsehocon', 'This function is deprecated, please use stdlib::parsehocon instead.', false)
call_function('stdlib::parsehocon', *args)
end
end

View file

@ -0,0 +1,34 @@
# frozen_string_literal: true
# @summary
# **Deprecated:** Starting Puppet 8, we no longer natively support PSON usage. This function should be removed once we stop supporting Puppet 7.
#
# This function accepts PSON, a Puppet variant of JSON, as a string and converts
# it into the correct Puppet structure
#
# @example How to parse pson
# $data = parsepson('{"a":"1","b":"2"}')
#
# For more information on PSON please see the following link:
# https://puppet.com/docs/puppet/7/http_api/pson.html
#
Puppet::Functions.create_function(:parsepson) do
# @param pson_string A valid PSON string
# @param default An optional default to return if parsing the pson_string fails
# @return [Data]
dispatch :parsepson do
param 'String[1]', :pson_string
optional_param 'Any', :default
end
def parsepson(pson_string, default = :no_default_provided)
call_function('deprecation', 'parsepson', 'This method is deprecated. From Puppet 8, PSON is no longer natively supported. Please use JSON.parse().')
PSON.load(pson_string) if Puppet::Util::Package.versioncmp(Puppet.version, '8').negative?
rescue StandardError => e
Puppet.debug("Parsing PSON failed with error: #{e.message}")
raise e if default == :no_default_provided
default
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::powershell_escape`](#stdlibpowershell_escape) instead.
Puppet::Functions.create_function(:powershell_escape) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'powershell_escape', 'This function is deprecated, please use stdlib::powershell_escape instead.', false)
call_function('stdlib::powershell_escape', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::seeded_rand`](#stdlibseeded_rand) instead.
Puppet::Functions.create_function(:seeded_rand) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'seeded_rand', 'This function is deprecated, please use stdlib::seeded_rand instead.', false)
call_function('stdlib::seeded_rand', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::seeded_rand_string`](#stdlibseeded_rand_string) instead.
Puppet::Functions.create_function(:seeded_rand_string) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'seeded_rand_string', 'This function is deprecated, please use stdlib::seeded_rand_string instead.', false)
call_function('stdlib::seeded_rand_string', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::shell_escape`](#stdlibshell_escape) instead.
Puppet::Functions.create_function(:shell_escape) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'shell_escape', 'This function is deprecated, please use stdlib::shell_escape instead.', false)
call_function('stdlib::shell_escape', *args)
end
end

View file

@ -0,0 +1,31 @@
# frozen_string_literal: true
# @summary
# Escapes a string so that it can be safely used in a batch shell command line.
#
# >* Note:* that the resulting string should be used unquoted and is not intended for use in double quotes nor in single
# quotes.
Puppet::Functions.create_function(:'stdlib::batch_escape') do
# @param string
# The string to escape
#
# @return
# An escaped string that can be safely used in a batch command line.
dispatch :batch_escape do
param 'Any', :string
end
def batch_escape(string)
result = ''
string.to_s.chars.each do |char|
result += case char
when '"' then '""'
when '$', '\\' then "\\#{char}"
else char
end
end
%("#{result}")
end
end

View file

@ -0,0 +1,31 @@
# frozen_string_literal: true
require 'zlib'
# @note
# The CRC32 algorithm can easily generate collisions,
# but may be useful for generating sharding, describing
# secrets, or seeding nonce values.
#
# @summary
# Run a CRC32 calculation against a given value.
Puppet::Functions.create_function(:'stdlib::crc32') do
# @param my_data The ScalarData to evaluate
# @example Check a simple string value
# stdlib::crc32('my string') == '18fbd270'
# @example Check a Sensitive datatype
# stdlib::crc32(sensitive('my string')) == '18fbd270'
# @example Check a number
# stdlib::crc32(100.0) == 'a3fd429a'
# stdlib::crc32(100.00000) == 'a3fd429a'
# @return String
dispatch :crc32 do
param 'Variant[ScalarData, Sensitive[ScalarData], Binary, Sensitive[Binary]]', :my_data
return_type 'String'
end
def crc32(my_data)
Zlib.crc32(my_data.unwrap.to_s).to_s(16).downcase
rescue StandardError
Zlib.crc32(my_data.to_s).to_s(16).downcase
end
end

View file

@ -0,0 +1,23 @@
# frozen_string_literal: true
# @summary
# Returns true if str ends with one of the prefixes given. Each of the prefixes should be a String.
#
Puppet::Functions.create_function(:'stdlib::end_with') do
# @param test_string The string to check
# @param suffixes The suffixes to check
# @example
# 'foobar'.stdlib::end_with('bar') => true
# 'foobar'.stdlib::end_with('foo') => false
# 'foobar'.stdlib::end_with(['foo', 'baz']) => false
# @return [Boolean] True or False
dispatch :end_with do
param 'String', :test_string
param 'Variant[String[1],Array[String[1], 1]]', :suffixes
return_type 'Boolean'
end
def end_with(test_string, suffixes)
test_string.end_with?(*suffixes)
end
end

View file

@ -0,0 +1,61 @@
# frozen_string_literal: true
# @summary Takes a list of packages and only installs them if they don't already exist.
#
# It optionally takes a hash as a second parameter that will be passed as the
# third argument to the ensure_resource() function.
Puppet::Functions.create_function(:'stdlib::ensure_packages', Puppet::Functions::InternalFunction) do
# @param packages
# The packages to ensure are installed.
# @param default_attributes
# Default attributes to be passed to the `ensure_resource()` function
# @return [Undef] Returns nothing.
dispatch :ensure_packages do
scope_param
param 'Variant[String[1], Array[String[1]]]', :packages
optional_param 'Hash', :default_attributes
return_type 'Undef'
end
# @param packages
# The packages to ensure are installed. The keys are packages and values are the attributes specific to that package.
# @param default_attributes
# Default attributes. Package specific attributes from the `packages` parameter will take precedence.
# @return [Undef] Returns nothing.
dispatch :ensure_packages_hash do
scope_param
param 'Hash[String[1], Any]', :packages
optional_param 'Hash', :default_attributes
return_type 'Undef'
end
def ensure_packages(scope, packages, default_attributes = {})
Array(packages).each do |package_name|
defaults = { 'ensure' => 'installed' }.merge(default_attributes)
# `present` and `installed` are aliases for the `ensure` attribute. If `ensure` is set to either of these values replace
# with `installed` by default but `present` if this package is already in the catalog with `ensure => present`
defaults['ensure'] = default_ensure(package_name) if ['present', 'installed'].include?(defaults['ensure'])
scope.call_function('ensure_resource', ['package', package_name, defaults])
end
nil
end
def ensure_packages_hash(scope, packages, default_attributes = {})
packages.each do |package, attributes|
ensure_packages(scope, package, default_attributes.merge(attributes))
end
nil
end
private
def default_ensure(package_name)
if call_function('defined_with_params', "Package[#{package_name}]", { 'ensure' => 'present' })
'present'
else
'installed'
end
end
end

View file

@ -0,0 +1,28 @@
# frozen_string_literal: true
# @summary
# Returns the Extension (the Portion of Filename in Path starting from the
# last Period).
#
# If Path is a Dotfile, or starts with a Period, then the starting Dot is not
# dealt with the Start of the Extension.
#
# An empty String will also be returned, when the Period is the last Character
# in Path.
Puppet::Functions.create_function(:'stdlib::extname') do
# @param filename The Filename
# @return [String] The Extension starting from the last Period
# @example Determining the Extension of a Filename
# stdlib::extname('test.rb') => '.rb'
# stdlib::extname('a/b/d/test.rb') => '.rb'
# stdlib::extname('test') => ''
# stdlib::extname('.profile') => ''
dispatch :extname do
param 'String', :filename
return_type 'String'
end
def extname(filename)
File.extname(filename)
end
end

View file

@ -0,0 +1,39 @@
# frozen_string_literal: true
# @summary
# Generates a random alphanumeric string. Combining the `$fqdn` fact and an
# optional seed for repeatable randomness.
#
# Optionally, you can specify a character set for the function (defaults to alphanumeric).
Puppet::Functions.create_function(:'stdlib::fqdn_rand_string') do
# @param length The length of the resulting string.
# @param charset The character set to use.
# @param seed The seed for repeatable randomness.
#
# @return [String]
#
# @example Example Usage:
# stdlib::fqdn_rand_string(10)
# stdlib::fqdn_rand_string(10, 'ABCDEF!@$%^')
# stdlib::fqdn_rand_string(10, undef, 'custom seed')
dispatch :fqdn_rand_string do
param 'Integer[1]', :length
optional_param 'Optional[String]', :charset
optional_repeated_param 'Any', :seed
end
def fqdn_rand_string(length, charset = nil, *seed)
charset = if charset && !charset.empty?
charset.chars.to_a
else
(0..9).map(&:to_s) + ('A'..'Z').to_a + ('a'..'z').to_a
end
rand_string = ''
length.times do |current|
rand_string += charset[call_function('fqdn_rand', charset.size, (seed + [current + 1]).join(':'))]
end
rand_string
end
end

View file

@ -0,0 +1,66 @@
# frozen_string_literal: true
# @summary Rotates an array or string a random number of times, combining the `fqdn` fact and an optional seed for repeatable randomness.
Puppet::Functions.create_function(:'stdlib::fqdn_rotate') do
# @param input
# The String you want rotated a random number of times
# @param seeds
# One of more values to use as a custom seed. These will be combined with the host's FQDN
#
# @return [String] Returns the rotated String
#
# @example Rotating a String
# stdlib::fqdn_rotate('abcd')
# @example Using a custom seed
# stdlib::fqdn_rotate('abcd', 'custom seed')
dispatch :fqdn_rotate_string do
param 'String', :input
optional_repeated_param 'Variant[Integer,String]', :seeds
return_type 'String'
end
# @param input
# The Array you want rotated a random number of times
# @param seeds
# One of more values to use as a custom seed. These will be combined with the host's FQDN
#
# @return [String] Returns the rotated Array
#
# @example Rotating an Array
# stdlib::fqdn_rotate(['a', 'b', 'c', 'd'])
# @example Using custom seeds
# stdlib::fqdn_rotate([1, 2, 3], 'custom', 'seed', 1)
dispatch :fqdn_rotate_array do
param 'Array', :input
optional_repeated_param 'Variant[Integer,String]', :seeds
return_type 'Array'
end
def fqdn_rotate_array(input, *seeds)
# Check whether it makes sense to rotate ...
return input if input.size <= 1
result = input.clone
require 'digest/md5'
seed = Digest::MD5.hexdigest([fqdn_fact, seeds].join(':')).hex
offset = Puppet::Util.deterministic_rand(seed, result.size).to_i
offset.times do
result.push result.shift
end
result
end
def fqdn_rotate_string(input, *seeds)
fqdn_rotate_array(input.chars, seeds).join
end
private
def fqdn_fact
closure_scope['facts']['networking']['fqdn']
end
end

View file

@ -0,0 +1,33 @@
# frozen_string_literal: true
# @summary
# Returns whether the Puppet runtime has access to a given function.
#
# @example Using stdlib::has_function()
# stdlib::has_function('stdlib::has_function') # true
# stdlib::has_function('not_a_function') # false
#
# Determines whether the Puppet runtime has access to a function by the
# name provided.
#
# @return
# Returns true if the provided function name is available, false otherwise.
#
Puppet::Functions.create_function(:'stdlib::has_function', Puppet::Functions::InternalFunction) do
dispatch :has_function do
scope_param
param 'String[1]', :function_name
return_type 'Boolean'
end
def has_function(scope, function_name) # rubocop:disable Naming/PredicateName
loaders = scope.compiler.loaders
loader = loaders.private_environment_loader
return true unless loader&.load(:function, function_name).nil?
# If the loader cannot find the function it might be
# a 3x-style function stubbed in on-the-fly for testing.
func_3x = Puppet::Parser::Functions.function(function_name.to_sym)
func_3x.is_a?(String) && !func_3x.empty?
end
end

View file

@ -0,0 +1,47 @@
# frozen_string_literal: true
# @summary Returns boolean based on network interfaces present and their attribute values.
#
# Can be called with one, or two arguments.
Puppet::Functions.create_function(:'stdlib::has_interface_with') do
# @param interface
# The name of an interface
# @return [Boolean] Returns `true` if `interface` exists and `false` otherwise
# @example When called with a single argument, the presence of the interface is checked
# stdlib::has_interface_with('lo') # Returns `true`
dispatch :has_interface do
param 'String[1]', :interface
return_type 'Boolean'
end
# @param kind
# A supported interface attribute
# @param value
# The value of the attribute
# @return [Boolean] Returns `true` if any of the interfaces in the `networking` fact has a `kind` attribute with the value `value`. Otherwise returns `false`
# @example Checking if an interface exists with a given mac address
# stdlib::has_interface_with('macaddress', 'x:x:x:x:x:x') # Returns `false`
# @example Checking if an interface exists with a given IP address
# stdlib::has_interface_with('ipaddress', '127.0.0.1') # Returns `true`
dispatch :has_interface_with do
param "Enum['macaddress','netmask','ipaddress','network','ip','mac']", :kind
param 'String[1]', :value
return_type 'Boolean'
end
def has_interface(interface) # rubocop:disable Naming/PredicateName
interfaces.key? interface
end
def has_interface_with(kind, value) # rubocop:disable Naming/PredicateName
# For compatibility with older version of function that used the legacy facts, alias `ip` with `ipaddress` and `mac` with `macaddress`
kind = 'ip' if kind == 'ipaddress'
kind = 'mac' if kind == 'macaddress'
interfaces.any? { |_interface, params| params[kind] == value }
end
def interfaces
closure_scope['facts']['networking']['interfaces']
end
end

View file

@ -0,0 +1,32 @@
# frozen_string_literal: true
# @summary
# Returns true if the ipaddress is within the given CIDRs
#
# @example ip_in_range(<IPv4 Address>, <IPv4 CIDR>)
# stdlib::ip_in_range('10.10.10.53', '10.10.10.0/24') => true
Puppet::Functions.create_function(:'stdlib::ip_in_range') do
# @param ipaddress The IP address to check
# @param range One CIDR or an array of CIDRs
# defining the range(s) to check against
#
# @return [Boolean] True or False
dispatch :ip_in_range do
param 'String', :ipaddress
param 'Variant[String, Array]', :range
return_type 'Boolean'
end
require 'ipaddr'
def ip_in_range(ipaddress, range)
ip = IPAddr.new(ipaddress)
if range.is_a? Array
ranges = range.map { |r| IPAddr.new(r) }
ranges.any? { |rng| rng.include?(ip) }
elsif range.is_a? String
ranges = IPAddr.new(range)
ranges.include?(ip)
end
end
end

View file

@ -0,0 +1,112 @@
# frozen_string_literal: true
# @summary
# Merges two or more hashes together or hashes resulting from iteration, and returns
# the resulting hash.
#
# @example Using stdlib::merge()
# $hash1 = {'one' => 1, 'two', => 2}
# $hash2 = {'two' => 'dos', 'three', => 'tres'}
# $merged_hash = stdlib::merge($hash1, $hash2) # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
#
# When there is a duplicate key, the key in the rightmost hash will "win."
#
# Note that since Puppet 4.0.0 the same merge can be achieved with the + operator.
# `$merged_hash = $hash1 + $hash2`
#
# If stdlib::merge is given a single Iterable (Array, Hash, etc.) it will call a given block with
# up to three parameters, and merge each resulting Hash into the accumulated result. All other types
# of values returned from the block (typically undef) are skipped (not merged).
#
# The codeblock can take 2 or three parameters:
# * with two, it gets the current hash (as built to this point), and each value (for hash the value is a [key, value] tuple)
# * with three, it gets the current hash (as built to this point), the key/index of each value, and then the value
#
# If the iterable is empty, or no hash was returned from the given block, an empty hash is returned. In the given block, a call to `next()`
# will skip that entry, and a call to `break()` will end the iteration.
#
# @example counting occurrences of strings in an array
# ['a', 'b', 'c', 'c', 'd', 'b'].stdlib::merge | $hsh, $v | { { $v => $hsh[$v].lest || { 0 } + 1 } } # results in { a => 1, b => 2, c => 2, d => 1 }
#
# @example skipping values for entries that are longer than 1 char
# ['a', 'b', 'c', 'c', 'd', 'b', 'blah', 'blah'].stdlib::merge | $hsh, $v | { if $v =~ String[1,1] { { $v => $hsh[$v].lest || { 0 } + 1 } } } # results in { a => 1, b => 2, c => 2, d => 1 }
#
# The iterative `stdlib::merge()` has an advantage over doing the same with a general `reduce()` in that the constructed hash
# does not have to be copied in each iteration and thus will perform much better with large inputs.
Puppet::Functions.create_function(:'stdlib::merge') do
# @param args
# Repeated Param - The hashes that are to be merged
#
# @return
# The merged hash
dispatch :merge2hashes do
repeated_param 'Variant[Hash[Scalar,Any], Undef, String[0,0]]', :args # this strange type is backwards compatible
return_type 'Hash[Scalar,Any]'
end
# @param args
# Repeated Param - The hashes that are to be merged
#
# @param block
# A block placed on the repeatable param `args`
#
# @return
# The merged hash
dispatch :merge_iterable3 do
repeated_param 'Iterable', :args
block_param 'Callable[3,3]', :block
return_type 'Hash'
end
# @param args
# Repeated Param - The hashes that are to be merged
#
# @param block
# A block placed on the repeatable param `args`
#
# @return
# The merged hash
dispatch :merge_iterable2 do
repeated_param 'Iterable', :args
block_param 'Callable[2,2]', :block
return_type 'Hash'
end
def merge2hashes(*hashes)
accumulator = {}
hashes.each { |h| accumulator.merge!(h) if h.is_a?(Hash) }
accumulator
end
def merge_iterable2(iterable)
accumulator = {}
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable)
enum.each do |v|
r = yield(accumulator, v)
accumulator.merge!(r) if r.is_a?(Hash)
end
accumulator
end
def merge_iterable3(iterable)
accumulator = {}
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable)
if enum.hash_style?
enum.each do |entry|
r = yield(accumulator, *entry)
accumulator.merge!(r) if r.is_a?(Hash)
end
else
begin
index = 0
loop do
r = yield(accumulator, index, enum.next)
accumulator.merge!(r) if r.is_a?(Hash)
index += 1
end
rescue StopIteration
end
end
accumulator
end
end

View file

@ -0,0 +1,27 @@
# frozen_string_literal: true
# @summary Get list of nested values from given hash
# This function will return list of nested Hash values and returns list of values in form of Array
#
# @example Example Usage:
# $hash = {
# "key1" => "value1",
# "key2" => { "key2.1" => "value2.1"},
# "key3" => "value3"
# }
# $data = $hash.stdlib::nested_values
# #Output : ["value1", "value2.1", "value3"]
Puppet::Functions.create_function(:'stdlib::nested_values') do
# @param hash A (nested) hash
# @return All the values found in the input hash included those deeply nested.
dispatch :nested_values do
param 'Hash', :hash
return_type 'Array'
end
def nested_values(hash)
hash.each_with_object([]) do |(_k, v), values|
v.is_a?(Hash) ? values.concat(nested_values(v)) : (values << v)
end
end
end

View file

@ -0,0 +1,27 @@
# frozen_string_literal: true
# @summary
# Checks if the OS version is at least a certain version.
# > *Note:*
# Only the major version is taken into account.
#
# @example Example usage:#
# if stdlib::os_version_gte('Debian', '9') { }
# if stdlib::os_version_gte('Ubuntu', '18.04') { }
Puppet::Functions.create_function(:'stdlib::os_version_gte') do
# @param os operating system
# @param version
#
# @return [Boolean] `true` or `false
dispatch :os_version_gte do
param 'String[1]', :os
param 'String[1]', :version
return_type 'Boolean'
end
def os_version_gte(os, version)
facts = closure_scope['facts']
(facts['os']['name'] == os &&
Puppet::Util::Package.versioncmp(facts['os']['release']['major'], version) >= 0)
end
end

View file

@ -0,0 +1,32 @@
# frozen_string_literal: true
# @summary
# This function accepts HOCON as a string and converts it into the correct
# Puppet structure
#
# @example How to parse hocon
# $data = stdlib::parsehocon("{any valid hocon: string}")
#
Puppet::Functions.create_function(:'stdlib::parsehocon') do
# @param hocon_string A valid HOCON string
# @param default An optional default to return if parsing hocon_string fails
# @return [Data]
dispatch :parsehocon do
param 'String', :hocon_string
optional_param 'Any', :default
end
def parsehocon(hocon_string, default = :no_default_provided)
require 'hocon/config_factory'
begin
data = Hocon::ConfigFactory.parse_string(hocon_string)
data.resolve.root.unwrapped
rescue Hocon::ConfigError::ConfigParseError => e
Puppet.debug("Parsing hocon failed with error: #{e.message}")
raise e if default == :no_default_provided
default
end
end
end

View file

@ -0,0 +1,31 @@
# frozen_string_literal: true
# @summary
# Escapes a string so that it can be safely used in a PowerShell command line.
#
# >* Note:* that the resulting string should be used unquoted and is not intended for use in double quotes nor in single
# quotes.
Puppet::Functions.create_function(:'stdlib::powershell_escape') do
# @param string
# The string to escape
#
# @return
# An escaped string that can be safely used in a PowerShell command line.
dispatch :powershell_escape do
param 'Any', :string
end
def powershell_escape(string)
result = ''
string.to_s.chars.each do |char|
result += case char
when ' ', "'", '`', '|', "\n", '$' then "`#{char}"
when '"' then '\`"'
else char
end
end
result
end
end

View file

@ -0,0 +1,22 @@
# frozen_string_literal: true
# @summary
# Generates a random whole number greater than or equal to 0 and less than max, using the value of seed for repeatable randomness.
Puppet::Functions.create_function(:'stdlib::seeded_rand') do
# @param max The maximum value.
# @param seed The seed used for repeatable randomness.
#
# @return [Integer]
# A random number greater than or equal to 0 and less than max
dispatch :seeded_rand do
param 'Integer[1]', :max
param 'String', :seed
end
def seeded_rand(max, seed)
require 'digest/md5'
seed = Digest::MD5.hexdigest(seed).hex
Puppet::Util.deterministic_rand_int(seed, max)
end
end

View file

@ -0,0 +1,32 @@
# frozen_string_literal: true
# @summary
# Generates a consistent random string of specific length based on provided seed.
#
# @example Generate a consistently random string of length 8 with a seed:
# stdlib::seeded_rand_string(8, "${module_name}::redis_password")
#
# @example Generate a random string from a specific set of characters:
# stdlib::seeded_rand_string(5, '', 'abcdef')
Puppet::Functions.create_function(:'stdlib::seeded_rand_string') do
# @param length Length of string to be generated.
# @param seed Seed string.
# @param charset String that contains characters to use for the random string.
#
# @return [String] Random string.
dispatch :rand_string do
param 'Integer[1]', :length
param 'String', :seed
optional_param 'String[2]', :charset
end
def rand_string(length, seed, charset = nil)
require 'digest/sha2'
charset ||= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
random_generator = Random.new(Digest::SHA256.hexdigest(seed).to_i(16))
Array.new(length) { charset[random_generator.rand(charset.size)] }.join
end
end

View file

@ -0,0 +1,26 @@
# frozen_string_literal: true
require 'digest'
# @summary
# Run a SHA256 calculation against a given value.
Puppet::Functions.create_function(:'stdlib::sha256') do
# @param my_data The ScalarData to evaluate
# @example Check a simple string value
# stdlib::sha256('my string') == '2f7e2089add0288a309abd71ffcc3b3567e2d4215e20e6ed3b74d6042f7ef8e5'
# @example Check a Sensitive datatype
# stdlib::sha256(sensitive('my string')) == '2f7e2089add0288a309abd71ffcc3b3567e2d4215e20e6ed3b74d6042f7ef8e5'
# @example Check a number
# stdlib::sha256(100.0) == '43b87f618caab482ebe4976c92bcd6ad308b48055f1c27b4c574f3e31d7683e0'
# stdlib::sha256(100.00000) == '43b87f618caab482ebe4976c92bcd6ad308b48055f1c27b4c574f3e31d7683e0'
# @return String
dispatch :sha256 do
param 'Variant[ScalarData, Sensitive[ScalarData], Binary, Sensitive[Binary]]', :my_data
return_type 'String'
end
def sha256(my_data)
Digest::SHA256.hexdigest(my_data.unwrap.to_s)
rescue StandardError
Digest::SHA256.hexdigest(my_data.to_s)
end
end

View file

@ -0,0 +1,25 @@
# frozen_string_literal: true
# @summary
# Escapes a string so that it can be safely used in a Bourne shell command line.
#
# >* Note:* that the resulting string should be used unquoted and is not intended for use in double quotes nor in single
# quotes.
#
# This function behaves the same as ruby's Shellwords.shellescape() function.
Puppet::Functions.create_function(:'stdlib::shell_escape') do
# @param string
# The string to escape
#
# @return
# An escaped string that can be safely used in a Bourne shell command line.
dispatch :shell_escape do
param 'Any', :string
end
def shell_escape(string)
require 'shellwords'
Shellwords.shellescape(string.to_s)
end
end

View file

@ -0,0 +1,49 @@
# frozen_string_literal: true
# @summary Sort an Array, Hash or String by mapping values through a given block.
#
# @example Sort local devices according to their used space.
# $facts['mountpoints'].stdlib::sort_by |$m| { $m.dig(1, 'used_bytes') }
#
Puppet::Functions.create_function(:'stdlib::sort_by') do
# @param ary The Array to sort.
# @param block The block for transforming elements of ary.
# @return [Array] Returns an ordered copy of ary.
dispatch :sort_by_array do
param 'Array', :ary
block_param 'Callable[1,1]', :block
end
# @param str The String to sort.
# @param block The block for transforming elements of str.
# @return [String] Returns an ordered copy of str.
dispatch :sort_by_string do
param 'String', :str
block_param 'Callable[1,1]', :block
end
# @param hsh The Hash to sort.
# @param block The block for transforming elements of hsh.
# The block may have arity of one or two.
# @return [Hash] Returns an ordered copy of hsh.
dispatch :sort_by_hash do
param 'Hash', :hsh
block_param 'Variant[Callable[1,1], Callable[2,2]]', :block
end
def sort_by_iterable(iterable, &block)
Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).sort_by(&block)
end
def sort_by_array(ary, &block)
sort_by_iterable(ary, &block)
end
def sort_by_string(str, &block)
sort_by_iterable(str, &block).join
end
def sort_by_hash(hsh, &block)
sort_by_iterable(hsh, &block).to_h
end
end

View file

@ -0,0 +1,23 @@
# frozen_string_literal: true
# @summary
# Returns true if str starts with one of the prefixes given. Each of the prefixes should be a String.
#
Puppet::Functions.create_function(:'stdlib::start_with') do
# @param test_string The string to check
# @param prefixes The prefixes to check.
# @example
# 'foobar'.stdlib::start_with('foo') => true
# 'foobar'.stdlib::start_with('bar') => false
# 'foObar'.stdlib::start_with(['bar', 'baz']) => false
# @return [Boolean] True or False
dispatch :start_with do
param 'String', :test_string
param 'Variant[String[1],Array[String[1], 1]]', :prefixes
return_type 'Boolean'
end
def start_with(test_string, prefixes)
test_string.start_with?(*prefixes)
end
end

View file

@ -0,0 +1,35 @@
# frozen_string_literal: true
# @summary
# This converts a string to a puppet resource.
#
# This attempts to convert a string like 'File[/foo]' into the
# puppet resource `File['/foo']` as detected by the catalog.
#
# Things like 'File[/foo, /bar]' are not supported as a
# title might contain things like ',' or ' '. There is
# no clear value seperator to use.
#
# This function can depend on the parse order of your
# manifests/modules as it inspects the catalog thus far.
Puppet::Functions.create_function(:'stdlib::str2resource') do
# @param res_string The string to lookup as a resource
# @example
# stdlib::str2resource('File[/foo]') => File[/foo]
# @return Puppet::Resource
dispatch :str2resource do
param 'String', :res_string
# return_type 'Puppet::Resource'
return_type 'Any'
end
def str2resource(res_string)
type_name, title = Puppet::Resource.type_and_title(res_string, nil)
resource = closure_scope.findresource(type_name, title)
raise(Puppet::ParseError, "stdlib::str2resource(): could not find #{type_name}[#{title}], this is parse order dependent and values should not be quoted") if resource.nil?
resource
end
end

View file

@ -0,0 +1,24 @@
# frozen_string_literal: true
require 'json'
# @summary
# Convert a data structure and output to JSON
Puppet::Functions.create_function(:'stdlib::to_json') do
# @param data
# Data structure which needs to be converted into JSON
#
# @example Output JSON to a file
# file { '/tmp/my.json':
# ensure => file,
# content => stdlib::to_json($myhash),
# }
#
# @return [String] Converted data to JSON
dispatch :to_json do
param 'Any', :data
end
def to_json(data)
data.to_json
end
end

View file

@ -0,0 +1,74 @@
# frozen_string_literal: true
require 'json'
# @summary
# Convert data structure and output to pretty JSON
#
# @example **Usage**
# * how to output pretty JSON to file
# file { '/tmp/my.json':
# ensure => file,
# content => stdlib::to_json_pretty($myhash),
# }
#
# * how to output pretty JSON skipping over keys with undef values
# file { '/tmp/my.json':
# ensure => file,
# content => stdlib::to_json_pretty({
# param_one => 'value',
# param_two => undef,
# }, true),
# }
#
# * how to output pretty JSON using tabs for indentation
# file { '/tmp/my.json':
# ensure => file,
# content => stdlib::to_json_pretty({
# param_one => 'value',
# param_two => {
# param_more => 42,
# },
# }, nil, {indent => ' '}),
# }
Puppet::Functions.create_function(:'stdlib::to_json_pretty') do
# @param data
# data structure which needs to be converted to pretty json
# @param skip_undef
# value `true` or `false`
# @param opts
# hash-map of settings passed to JSON.pretty_generate, see
# https://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-generate.
# Note that `max_nesting` doesn't take the value `false`; use `-1` instead.
# @return
# converted data to pretty json
dispatch :to_json_pretty do
param 'Variant[Hash, Array]', :data
optional_param 'Optional[Boolean]', :skip_undef
optional_param 'Struct[{
indent => Optional[String],
space => Optional[String],
space_before => Optional[String],
object_nl => Optional[String],
array_nl => Optional[String],
allow_nan => Optional[Boolean],
max_nesting => Optional[Integer[-1,default]],
}]', :opts
end
def to_json_pretty(data, skip_undef = false, opts = nil)
# It's not possible to make an abstract type that can be either a boolean
# false or an integer, so we use -1 as the falsey value
if opts
opts = opts.transform_keys(&:to_sym)
opts[:max_nesting] = false if opts[:max_nesting] == -1
end
data = data.compact if skip_undef && (data.is_a?(Array) || Hash)
# Call ::JSON to ensure it references the JSON library from Ruby's standard library
# instead of a random JSON namespace that might be in scope due to user code.
JSON.pretty_generate(data, opts) << "\n"
end
end

View file

@ -0,0 +1,42 @@
# frozen_string_literal: true
# @summary
# Convert an object into a String containing its Python representation
#
# @example how to output Python
# # output Python to a file
# $listen = '0.0.0.0'
# $port = 8000
# file { '/opt/acme/etc/settings.py':
# content => inline_epp(@("SETTINGS")),
# LISTEN = <%= stdlib::to_python($listen) %>
# PORT = <%= stdlib::to_python($mailserver) %>
# | SETTINGS
# }
Puppet::Functions.create_function(:'stdlib::to_python') do
# @param object
# The object to be converted
#
# @return [String]
# The String representation of the object
dispatch :to_python do
param 'Any', :object
end
def to_python(object)
serialized = Puppet::Pops::Serialization::ToDataConverter.convert(object, rich_data: true)
serialized_to_python(serialized)
end
def serialized_to_python(serialized)
case serialized
when true then 'True'
when false then 'False'
when nil then 'None'
when Array then "[#{serialized.map { |x| serialized_to_python(x) }.join(', ')}]"
when Hash then "{#{serialized.map { |k, v| "#{serialized_to_python(k)}: #{serialized_to_python(v)}" }.join(', ')}}"
else serialized.inspect
end
end
end

View file

@ -0,0 +1,39 @@
# frozen_string_literal: true
# @summary
# Convert an object into a String containing its Ruby representation
#
# @example how to output Ruby
# # output Ruby to a file
# $listen = '0.0.0.0'
# $port = 8000
# file { '/opt/acme/etc/settings.rb':
# content => inline_epp(@("SETTINGS")),
# LISTEN = <%= stdlib::to_ruby($listen) %>
# PORT = <%= stdlib::to_ruby($mailserver) %>
# | SETTINGS
# }
Puppet::Functions.create_function(:'stdlib::to_ruby') do
# @param object
# The object to be converted
#
# @return [String]
# The String representation of the object
dispatch :to_ruby do
param 'Any', :object
end
def to_ruby(object)
serialized = Puppet::Pops::Serialization::ToDataConverter.convert(object, rich_data: true)
serialized_to_ruby(serialized)
end
def serialized_to_ruby(serialized)
case serialized
when Array then "[#{serialized.map { |x| serialized_to_ruby(x) }.join(', ')}]"
when Hash then "{#{serialized.map { |k, v| "#{serialized_to_ruby(k)} => #{serialized_to_ruby(v)}" }.join(', ')}}"
else serialized.inspect
end
end
end

View file

@ -0,0 +1,22 @@
# frozen_string_literal: true
require_relative '../../../puppet_x/stdlib/toml_dumper'
# @summary Convert a data structure and output to TOML.
Puppet::Functions.create_function(:'stdlib::to_toml') do
# @param data Data structure which needs to be converted into TOML
# @return [String] Converted data as TOML string
# @example How to output TOML to a file
# file { '/tmp/config.toml':
# ensure => file,
# content => stdlib::to_toml($myhash),
# }
dispatch :to_toml do
required_param 'Hash', :data
return_type 'String'
end
def to_toml(data)
PuppetX::Stdlib::TomlDumper.new(data).toml_str
end
end

View file

@ -0,0 +1,32 @@
# frozen_string_literal: true
require 'yaml'
# @summary
# Convert a data structure and output it as YAML
Puppet::Functions.create_function(:'stdlib::to_yaml') do
# @param data
# The data you want to convert to YAML
# @param options
# A hash of options that will be passed to Ruby's Psych library. Note, this could change between Puppet versions, but at time of writing these are `line_width`, `indentation`, and `canonical`.
#
# @example Output YAML to a file
# file { '/tmp/my.yaml':
# ensure => file,
# content => stdlib::to_yaml($myhash),
# }
# @example Use options to control the output format
# file { '/tmp/my.yaml':
# ensure => file,
# content => stdlib::to_yaml($myhash, {indentation => 4})
# }
#
# @return [String] The YAML document
dispatch :to_yaml do
param 'Any', :data
optional_param 'Hash', :options
end
def to_yaml(data, options = {})
data.to_yaml(options.transform_keys(&:to_sym))
end
end

View file

@ -0,0 +1,26 @@
# frozen_string_literal: true
# @summary
# Returns the type of the passed value.
#
# @example how to compare values' types
# # compare the types of two values
# if stdlib::type_of($first_value) != stdlib::type_of($second_value) { fail("first_value and second_value are different types") }
# @example how to compare against an abstract type
# unless stdlib::type_of($first_value) <= Numeric { fail("first_value must be Numeric") }
# unless stdlib::type_of{$first_value) <= Collection[1] { fail("first_value must be an Array or Hash, and contain at least one element") }
#
# See the documentation for "The Puppet Type System" for more information about types.
# See the `assert_type()` function for flexible ways to assert the type of a value.
#
# The built-in type() function in puppet is generally preferred over this function
# this function is provided for backwards compatibility.
Puppet::Functions.create_function(:'stdlib::type_of') do
# @return [String]
# the type of the passed value
#
# @param value
def type_of(value)
Puppet::Pops::Types::TypeCalculator.infer_set(value)
end
end

View file

@ -0,0 +1,34 @@
# frozen_string_literal: true
# @summary
# Validate that all values passed are syntactically correct domain names.
# Fail compilation if any value fails this check.
Puppet::Functions.create_function(:'stdlib::validate_domain_name') do
# @param values A domain name or an array of domain names to check
#
# @return [Undef]
# passes when the given values are syntactically correct domain names or raise an error when they are not and fails compilation
#
# @example Passing examples
# $my_domain_name = 'server.domain.tld'
# stdlib::validate_domain_name($my_domain_name)
# stdlib::validate_domain_name('domain.tld', 'puppet.com', $my_domain_name)
# stdlib::validate_domain_name('www.example.2com')
#
# @example Failing examples (causing compilation to abort)
# stdlib::validate_domain_name(1)
# stdlib::validate_domain_name(true)
# stdlib::validate_domain_name('invalid domain')
# stdlib::validate_domain_name('-foo.example.com')
dispatch :validate_domain_name do
repeated_param 'Variant[Stdlib::Fqdn, Stdlib::Dns::Zone]', :values
end
def validate_domain_name(*args)
assert_arg_count(args)
end
def assert_arg_count(args)
raise(ArgumentError, 'stdlib::validate_domain_name(): Wrong number of arguments need at least one') if args.empty?
end
end

View file

@ -0,0 +1,31 @@
# frozen_string_literal: true
# @summary
# Validate that all values passed are valid email addresses.
# Fail compilation if any value fails this check.
Puppet::Functions.create_function(:'stdlib::validate_email_address') do
# @param values An e-mail address or an array of e-mail addresses to check
#
# @return [Undef]
# Fail compilation if any value fails this check.
#
# @example Passing examples
# $my_email = "waldo@gmail.com"
# stdlib::validate_email_address($my_email)
# stdlib::validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email)
#
# @example Failing examples (causing compilation to abort)
# $some_array = [ 'bad_email@/d/efdf.com' ]
# stdlib::validate_email_address($some_array)
dispatch :validate_email_address do
repeated_param 'Stdlib::Email', :values
end
def validate_email_address(*args)
assert_arg_count(args)
end
def assert_arg_count(args)
raise(ArgumentError, 'stdlib::validate_email_address(): Wrong number of arguments need at least one') if args.empty?
end
end

View file

@ -0,0 +1,30 @@
# frozen_string_literal: true
# @summary Encode strings for XML files
#
# This function can encode strings such that they can be used directly in XML files.
# It supports encoding for both XML text (CharData) or attribute values (AttValue).
Puppet::Functions.create_function(:'stdlib::xml_encode') do
# @param str The string to encode
# @param type Whether to encode for text or an attribute
# @return Returns the encoded CharData or AttValue string suitable for use in XML
# @example Creating an XML file from a template
# file { '/path/to/config.xml':
# ensure => file,
# content => epp(
# 'mymodule/config.xml.epp',
# {
# password => $password.stdlib::xml_encode,
# },
# ),
# }
dispatch :xml_encode do
param 'String', :str
optional_param "Enum['text','attr']", :type
return_type 'String'
end
def xml_encode(str, type = 'text')
str.encode(xml: type.to_sym)
end
end

View file

@ -0,0 +1,12 @@
# frozen_string_literal: true
# @summary DEPRECATED. Use the native Puppet fuctionality instead of this function. eg `Integer(Timestamp().strftime('%s'))`
Puppet::Functions.create_function(:time) do
dispatch :call_puppet_function do
repeated_param 'Any', :args
end
def call_puppet_function(*args)
# Note, `stdlib::time` calls `deprecation`, so we don't also do that here.
call_function('stdlib::time', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_json`](#stdlibto_json) instead.
Puppet::Functions.create_function(:to_json) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_json', 'This function is deprecated, please use stdlib::to_json instead.', false)
call_function('stdlib::to_json', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_json_pretty`](#stdlibto_json_pretty) instead.
Puppet::Functions.create_function(:to_json_pretty) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_json_pretty', 'This function is deprecated, please use stdlib::to_json_pretty instead.', false)
call_function('stdlib::to_json_pretty', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_python`](#stdlibto_python) instead.
Puppet::Functions.create_function(:to_python) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_python', 'This function is deprecated, please use stdlib::to_python instead.', false)
call_function('stdlib::to_python', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_ruby`](#stdlibto_ruby) instead.
Puppet::Functions.create_function(:to_ruby) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_ruby', 'This function is deprecated, please use stdlib::to_ruby instead.', false)
call_function('stdlib::to_ruby', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_toml`](#stdlibto_toml) instead.
Puppet::Functions.create_function(:to_toml) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_toml', 'This function is deprecated, please use stdlib::to_toml instead.', false)
call_function('stdlib::to_toml', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::to_yaml`](#stdlibto_yaml) instead.
Puppet::Functions.create_function(:to_yaml) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'to_yaml', 'This function is deprecated, please use stdlib::to_yaml instead.', false)
call_function('stdlib::to_yaml', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::type_of`](#stdlibtype_of) instead.
Puppet::Functions.create_function(:type_of) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'type_of', 'This function is deprecated, please use stdlib::type_of instead.', false)
call_function('stdlib::type_of', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::validate_domain_name`](#stdlibvalidate_domain_name) instead.
Puppet::Functions.create_function(:validate_domain_name) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'validate_domain_name', 'This function is deprecated, please use stdlib::validate_domain_name instead.', false)
call_function('stdlib::validate_domain_name', *args)
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`
# @summary DEPRECATED. Use the namespaced function [`stdlib::validate_email_address`](#stdlibvalidate_email_address) instead.
Puppet::Functions.create_function(:validate_email_address) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', 'validate_email_address', 'This function is deprecated, please use stdlib::validate_email_address instead.', false)
call_function('stdlib::validate_email_address', *args)
end
end

View file

@ -0,0 +1,68 @@
# frozen_string_literal: true
# @summary
# **Deprecated:** Validate a value against both the target_type (new).
Puppet::Functions.create_function(:validate_legacy) do
# The function checks a value against both the target_type (new).
# @param scope
# The main value that will be passed to the method
# @param target_type
# @param function_name
# Unused
# @param value
# @param args
# Any additional values that are to be passed to the method
# @return
# A boolean value (`true` or `false`) returned from the called function.
dispatch :validate_legacy do
param 'Any', :scope
param 'Type', :target_type
param 'String', :function_name
param 'Any', :value
repeated_param 'Any', :args
end
# @param scope
# The main value that will be passed to the method
# @param type_string
# @param function_name
# Unused
# @param value
# @param args Any additional values that are to be passed to the method
# @return Legacy validation method
#
dispatch :validate_legacy_s do
param 'Any', :scope
param 'String', :type_string
param 'String', :function_name
param 'Any', :value
repeated_param 'Any', :args
end
# Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-
# c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1.
def call(scope, *args)
manipulated_args = [scope] + args
self.class.dispatcher.dispatch(self, scope, manipulated_args)
end
def validate_legacy_s(scope, type_string, *args)
t = Puppet::Pops::Types::TypeParser.new.parse(type_string, scope)
validate_legacy(scope, t, *args)
end
def validate_legacy(_scope, target_type, _function_name, value, *_prev_args)
call_function('deprecation', 'validate_legacy', 'This method is deprecated, please use Puppet data types to validate parameters')
if assert_type(target_type, value)
# "Silently" passes
else
inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value)
error_msg = Puppet::Pops::Types::TypeMismatchDescriber.new.describe_mismatch("validate_legacy(#{target_type}, ...)", target_type, inferred_type)
call_function('fail', error_msg)
end
end
def assert_type(type, value)
Puppet::Pops::Types::TypeCalculator.instance?(type, value)
end
end