Skip to content

Namespace Puppet 4.x functions #1356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Lint/MissingCopEnableDirective:
# Configuration parameters: AllowComments, AllowNil.
Lint/SuppressedException:
Exclude:
- 'lib/puppet/functions/merge.rb'
- 'lib/puppet/functions/stdlib/merge.rb'
- 'lib/puppet/parser/functions/has_interface_with.rb'

# Offense count: 5
Expand Down Expand Up @@ -93,7 +93,7 @@ Naming/VariableNumber:
# Configuration parameters: MinSize.
Performance/CollectionLiteralInLoop:
Exclude:
- 'lib/puppet/functions/ensure_packages.rb'
- 'lib/puppet/functions/stdlib/ensure_packages.rb'

# Offense count: 36
# Configuration parameters: Prefixes, AllowedPatterns.
Expand Down Expand Up @@ -192,5 +192,5 @@ Style/MixinUsage:
# AllowedMethods: respond_to_missing?
Style/OptionalBooleanParameter:
Exclude:
- 'lib/puppet/functions/to_json_pretty.rb'
- 'lib/puppet/functions/stdlib/to_json_pretty.rb'
- 'lib/puppet_x/stdlib/toml_dumper.rb'
30 changes: 30 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,33 @@ EOM
end
end

desc 'Regenerate the deprecated unamespaced shims'
task :regenerate_unamespaced_shims do
Dir['lib/puppet/functions/*.rb'].each do |filename|
content = File.read(filename)

unless content =~ /@summary DEPRECATED. Use the namespaced function/
warn("#{filename} does not look like a deprecation shim (skipping)")
next
end

function_name = File.basename(filename, '.rb')

File.write(filename, <<~CODE)
# frozen_string_literal: true

# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`

# @summary DEPRECATED. Use the namespaced function [`stdlib::#{function_name}`](#stdlib#{function_name}) instead.
Puppet::Functions.create_function(:#{function_name}) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
end
def deprecation_gen(*args)
call_function('deprecation', '#{function_name}', 'This function is deprecated, please use stdlib::#{function_name} instead.')
call_function('stdlib::#{function_name}', *args)
end
end
CODE
end
end
33 changes: 8 additions & 25 deletions lib/puppet/functions/batch_escape.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,14 @@
# 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.
# 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
# @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
dispatch :deprecation_gen do
repeated_param 'Any', :args
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}")
def deprecation_gen(*args)
call_function('deprecation', 'batch_escape', 'This function is deprecated, please use stdlib::batch_escape instead.')
call_function('stdlib::batch_escape', *args)
end
end
63 changes: 8 additions & 55 deletions lib/puppet/functions/ensure_packages.rb
Original file line number Diff line number Diff line change
@@ -1,61 +1,14 @@
# 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(: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'])
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`

scope.call_function('ensure_resource', ['package', package_name, defaults])
end
nil
# @summary DEPRECATED. Use the namespaced function [`stdlib::ensure_packages`](#stdlibensure_packages) instead.
Puppet::Functions.create_function(:ensure_packages) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
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
def deprecation_gen(*args)
call_function('deprecation', 'ensure_packages', 'This function is deprecated, please use stdlib::ensure_packages instead.')
call_function('stdlib::ensure_packages', *args)
end
end
39 changes: 8 additions & 31 deletions lib/puppet/functions/fqdn_rand_string.rb
Original file line number Diff line number Diff line change
@@ -1,37 +1,14 @@
# 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).
# 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
# @param length The length of the resulting string.
# @param charset The character set to use.
# @param The seed for repeatable randomness.
#
# @return [String]
#
# @example Example Usage:
# fqdn_rand_string(10)
# fqdn_rand_string(10, 'ABCDEF!@$%^')
# fqdn_rand_string(10, '', 'custom seed')
dispatch :fqdn_rand_string do
param 'Integer[1]', :length
optional_param 'String', :charset
optional_repeated_param 'Any', :seed
dispatch :deprecation_gen do
repeated_param 'Any', :args
end

def fqdn_rand_string(length, charset = '', *seed)
charset = charset.chars.to_a

charset = (0..9).map(&:to_s) + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty?

rand_string = ''
length.times do |current|
rand_string += charset[call_function('fqdn_rand', charset.size, (seed + [current + 1]).join(':'))]
end

rand_string
def deprecation_gen(*args)
call_function('deprecation', 'fqdn_rand_string', 'This function is deprecated, please use stdlib::fqdn_rand_string instead.')
call_function('stdlib::fqdn_rand_string', *args)
end
end
4 changes: 3 additions & 1 deletion lib/puppet/functions/has_interface_with.rb
Original file line number Diff line number Diff line change
@@ -1,12 +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 method is deprecated, please use stdlib::has_interface_with instead.')
call_function('deprecation', 'has_interface_with', 'This function is deprecated, please use stdlib::has_interface_with instead.')
call_function('stdlib::has_interface_with', *args)
end
end
114 changes: 8 additions & 106 deletions lib/puppet/functions/merge.rb
Original file line number Diff line number Diff line change
@@ -1,112 +1,14 @@
# frozen_string_literal: true

# @summary
# Merges two or more hashes together or hashes resulting from iteration, and returns
# the resulting hash.
#
# @example Using merge()
# $hash1 = {'one' => 1, 'two', => 2}
# $hash2 = {'two' => 'dos', 'three', => 'tres'}
# $merged_hash = 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 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'].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'].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 `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(: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
# THIS FILE WAS GENERATED BY `rake regenerate_unamespaced_shims`

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
# @summary DEPRECATED. Use the namespaced function [`stdlib::merge`](#stdlibmerge) instead.
Puppet::Functions.create_function(:merge) do
dispatch :deprecation_gen do
repeated_param 'Any', :args
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
def deprecation_gen(*args)
call_function('deprecation', 'merge', 'This function is deprecated, please use stdlib::merge instead.')
call_function('stdlib::merge', *args)
end
end
29 changes: 8 additions & 21 deletions lib/puppet/functions/os_version_gte.rb
Original file line number Diff line number Diff line change
@@ -1,27 +1,14 @@
# 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 os_version_gte('Debian', '9') { }
# if os_version_gte('Ubuntu', '18.04') { }
# 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
# @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'
dispatch :deprecation_gen do
repeated_param 'Any', :args
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)
def deprecation_gen(*args)
call_function('deprecation', 'os_version_gte', 'This function is deprecated, please use stdlib::os_version_gte instead.')
call_function('stdlib::os_version_gte', *args)
end
end
Loading