diff --git a/lib/facter/package_provider.rb b/lib/facter/package_provider.rb index 572eb4f..02a1724 100644 --- a/lib/facter/package_provider.rb +++ b/lib/facter/package_provider.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true # Fact: package_provider # # Purpose: Returns the default provider Puppet will choose to manage packages # on this system # # Resolution: Instantiates a dummy package resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/package' # These will be nil if Puppet is not available. Facter.add(:package_provider) do # Instantiates a dummy package resource and return the provider setcode do if defined? Gem && Gem::Version.new(Facter.value(:puppetversion).split(' ')[0]) >= Gem::Version.new('3.6') - Puppet::Type.type(:package).newpackage(:name => 'dummy', :allow_virtual => 'true')[:provider].to_s + Puppet::Type.type(:package).newpackage(name: 'dummy', allow_virtual: 'true')[:provider].to_s else - Puppet::Type.type(:package).newpackage(:name => 'dummy')[:provider].to_s + Puppet::Type.type(:package).newpackage(name: 'dummy')[:provider].to_s end end end diff --git a/lib/facter/pe_version.rb b/lib/facter/pe_version.rb index 901dd6c..9f51431 100644 --- a/lib/facter/pe_version.rb +++ b/lib/facter/pe_version.rb @@ -1,72 +1,72 @@ # frozen_string_literal: true # Fact: is_pe, pe_version, pe_major_version, pe_minor_version, pe_patch_version # # Purpose: Return various facts about the PE state of the system # # Resolution: Uses a regex match against puppetversion to determine whether the # machine has Puppet Enterprise installed, and what version (overall, major, # minor, patch) is installed. # # Caveats: # # Fact: pe_version Facter.add('pe_version') do setcode do found_version = Facter.value('pe_build') unless found_version puppet_ver = Facter.value('puppetversion') unless puppet_ver.nil? pe_ver = puppet_ver.match(%r{Puppet Enterprise (\d+\.\d+\.\d+)}) found_version = pe_ver[1] if pe_ver end end found_version end end # Fact: is_pe Facter.add('is_pe') do setcode do if Facter.value(:pe_version).to_s.empty? false else true end end end # Fact: pe_major_version Facter.add('pe_major_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[0] end end end # Fact: pe_minor_version Facter.add('pe_minor_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[1] end end end # Fact: pe_patch_version Facter.add('pe_patch_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[2] end end end diff --git a/lib/facter/root_home.rb b/lib/facter/root_home.rb index 9745481..8b11f2a 100644 --- a/lib/facter/root_home.rb +++ b/lib/facter/root_home.rb @@ -1,49 +1,49 @@ # frozen_string_literal: true # root_home.rb module Facter::Util::RootHome # @summary # A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. class << self - # determines the root home directory - def returnt_root_home - root_ent = Facter::Util::Resolution.exec('getent passwd root') - # The home directory is the sixth element in the passwd entry - # If the platform doesn't have getent, root_ent will be nil and we should - # return it straight away. - root_ent && root_ent.split(':')[5] - end + # determines the root home directory + def returnt_root_home + root_ent = Facter::Util::Resolution.exec('getent passwd root') + # The home directory is the sixth element in the passwd entry + # If the platform doesn't have getent, root_ent will be nil and we should + # return it straight away. + root_ent && root_ent.split(':')[5] + end end end Facter.add(:root_home) do setcode { Facter::Util::RootHome.returnt_root_home } end Facter.add(:root_home) do - confine :kernel => :darwin + confine kernel: :darwin setcode do str = Facter::Util::Resolution.exec('dscacheutil -q user -a name root') hash = {} str.split("\n").each do |pair| key, value = pair.split(%r{:}) hash[key] = value end hash['dir'].strip end end Facter.add(:root_home) do - confine :kernel => :aix + confine kernel: :aix root_home = nil setcode do str = Facter::Util::Resolution.exec('lsuser -c -a home root') str && str.split("\n").each do |line| - next if line =~ %r{^#} + next if %r{^#}.match?(line) root_home = line.split(%r{:})[1] end root_home end end diff --git a/lib/facter/service_provider.rb b/lib/facter/service_provider.rb index 4782928..3d4e44a 100644 --- a/lib/facter/service_provider.rb +++ b/lib/facter/service_provider.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true # Fact: service_provider # # Purpose: Returns the default provider Puppet will choose to manage services # on this system # # Resolution: Instantiates a dummy service resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/service' Facter.add(:service_provider) do setcode do - Puppet::Type.type(:service).newservice(:name => 'dummy')[:provider].to_s + Puppet::Type.type(:service).newservice(name: 'dummy')[:provider].to_s end end diff --git a/lib/puppet/functions/deprecation.rb b/lib/puppet/functions/deprecation.rb index 5b9aa21..f71924f 100644 --- a/lib/puppet/functions/deprecation.rb +++ b/lib/puppet/functions/deprecation.rb @@ -1,40 +1,40 @@ # frozen_string_literal: true # Function to print deprecation warnings, Logs a warning once for a given key. # # 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. # It 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) *Type*: String, String. # Puppet::Functions.create_function(:deprecation) do # @param key # @param message # @return deprecated warnings dispatch :deprecation do param 'String', :key param 'String', :message end def deprecation(key, message) if defined? Puppet::Pops::PuppetStack.stacktrace stacktrace = Puppet::Pops::PuppetStack.stacktrace() file = stacktrace[0] line = stacktrace[1] message = "#{message} at #{file}:#{line}" end # depending on configuration setting of strict case Puppet.settings[:strict] - when :off # rubocop:disable Lint/EmptyWhen : Is required to prevent false errors + when :off # do nothing when :error raise("deprecation. #{key}. #{message}") else unless ENV['STDLIB_LOG_DEPRECATIONS'] == 'false' Puppet.deprecation_warning(message, key) end end end end diff --git a/lib/puppet/functions/merge.rb b/lib/puppet/functions/merge.rb index 7d93c30..d94a793 100644 --- a/lib/puppet/functions/merge.rb +++ b/lib/puppet/functions/merge.rb @@ -1,112 +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 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, Undef, String[0,0]]', :args # this strange type is backwards compatible 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_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 # rubocop:disable Lint/HandleExceptions + rescue StopIteration end end accumulator end end diff --git a/lib/puppet/parser/functions/abs.rb b/lib/puppet/parser/functions/abs.rb index 4c828f1..822bc5d 100644 --- a/lib/puppet/parser/functions/abs.rb +++ b/lib/puppet/parser/functions/abs.rb @@ -1,45 +1,44 @@ # frozen_string_literal: true # # abs.rb # module Puppet::Parser::Functions - newfunction(:abs, :type => :rvalue, :doc => <<-DOC + newfunction(:abs, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the absolute value of a number For example -34.56 becomes 34.56. Takes a single integer or float value as an argument. > *Note:* **Deprected** from Puppet 6.0.0, the built-in ['abs'](https://puppet.com/docs/puppet/6.4/function.html#abs)function will be used instead. @return The absolute value of the given number if it was an Integer DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "abs(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] # Numbers in Puppet are often string-encoded which is troublesome ... if value.is_a?(String) - if value =~ %r{^-?(?:\d+)(?:\.\d+){1}$} + if %r{^-?(?:\d+)(?:\.\d+){1}$}.match?(value) value = value.to_f - elsif value =~ %r{^-?\d+$} + elsif %r{^-?\d+$}.match?(value) value = value.to_i else raise(Puppet::ParseError, 'abs(): Requires float or integer to work with') end end # We have numeric value to handle ... result = value.abs return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/any2array.rb b/lib/puppet/parser/functions/any2array.rb index bbffeab..107c11d 100644 --- a/lib/puppet/parser/functions/any2array.rb +++ b/lib/puppet/parser/functions/any2array.rb @@ -1,58 +1,57 @@ # frozen_string_literal: true # # any2array.rb # module Puppet::Parser::Functions - newfunction(:any2array, :type => :rvalue, :doc => <<-DOC + newfunction(:any2array, type: :rvalue, doc: <<-DOC @summary This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. > *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 [`Array.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-array-and-tuple) function is used to create a new Array.. ``` $hsh = {'key' => 42, 'another-key' => 100} notice(Array($hsh)) ``` Would notice `[['key', 42], ['another-key', 100]]` The Array data type also has a special mode to "create an array if not already an array" ``` notice(Array({'key' => 42, 'another-key' => 100}, true)) ``` Would notice `[{'key' => 42, 'another-key' => 100}]`, as the `true` flag prevents the hash from being transformed into an array. @return [Array] The new array containing the given object DOC - ) do |arguments| - + ) do |arguments| if arguments.empty? return [] end return arguments unless arguments.length == 1 return arguments[0] if arguments[0].is_a?(Array) return [] if arguments == [''] if arguments[0].is_a?(Hash) result = [] arguments[0].each do |key, value| result << key << value end return result end return arguments end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/any2bool.rb b/lib/puppet/parser/functions/any2bool.rb index 304d11b..0215d19 100644 --- a/lib/puppet/parser/functions/any2bool.rb +++ b/lib/puppet/parser/functions/any2bool.rb @@ -1,62 +1,61 @@ # frozen_string_literal: true # # any2bool.rb # module Puppet::Parser::Functions - newfunction(:any2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:any2bool, type: :rvalue, doc: <<-DOC @summary Converts 'anything' to a boolean. In practise it does the following: * Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true * Strings such as 0,F,f,N,n,FALSE,no,'false' will return false * Booleans will just return their original value * Number (or a string representation of a number) > 0 will return true, otherwise false * undef will return false * Anything else will return true Also see the built-in [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean) function. @return [Boolean] The boolean value of the object that was given DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? # If argument is already Boolean, return it if !!arguments[0] == arguments[0] # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean return arguments[0] end arg = arguments[0] if arg.nil? return false end if arg == :undef return false end valid_float = begin !!Float(arg) # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean rescue false end if arg.is_a?(Numeric) return function_num2bool([arguments[0]]) end if arg.is_a?(String) return function_num2bool([arguments[0]]) if valid_float return function_str2bool([arguments[0]]) end return true end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/assert_private.rb b/lib/puppet/parser/functions/assert_private.rb index ed892d4..5c504b0 100644 --- a/lib/puppet/parser/functions/assert_private.rb +++ b/lib/puppet/parser/functions/assert_private.rb @@ -1,34 +1,33 @@ # frozen_string_literal: true # # assert_private.rb # module Puppet::Parser::Functions - newfunction(:assert_private, :doc => <<-DOC + newfunction(:assert_private, doc: <<-DOC @summary Sets the current class or definition as private. @return set the current class or definition as private. Calling the class or definition from outside the current module will fail. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "assert_private(): Wrong number of arguments given (#{args.size}}) for 0 or 1)") if args.size > 1 scope = self if scope.lookupvar('module_name') != scope.lookupvar('caller_module_name') message = nil if args[0] && args[0].is_a?(String) message = args[0] else manifest_name = scope.source.name manifest_type = scope.source.type message = (manifest_type.to_s == 'hostclass') ? 'Class' : 'Definition' message += " #{manifest_name} is private" end raise(Puppet::ParseError, message) end end end diff --git a/lib/puppet/parser/functions/base64.rb b/lib/puppet/parser/functions/base64.rb index 47e9e31..1fe2751 100644 --- a/lib/puppet/parser/functions/base64.rb +++ b/lib/puppet/parser/functions/base64.rb @@ -1,87 +1,87 @@ # frozen_string_literal: true # 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(:base64, :type => :rvalue, :doc => <<-DOC) do |args| + newfunction(:base64, type: :rvalue, doc: <<-DOC) do |args| @summary Base64 encode or decode a string based on the command and the string submitted @example Example usage Encode and decode a string $encodestring = base64('encode', 'thestring') $decodestring = base64('decode', 'dGhlc3RyaW5n') Explicitly define encode/decode method: default, strict, urlsafe $method = 'default' $encodestring = base64('encode', 'thestring', $method) $decodestring = base64('decode', 'dGhlc3RyaW5n', $method) Encode a string as if it was binary $encodestring = String(Binary('thestring', '%s')) Decode a Binary assuming it is an UTF-8 String $decodestring = String(Binary("dGhlc3RyaW5n"), "%s") > **Note:* Since Puppet 4.8.0, the Binary data type can be used to produce base 64 encoded strings. See the `new()` function for the Binary and String types for documentation. Also see `binary_file()` function for reading a file with binary (non UTF-8) content. @return [String] The encoded/decoded value DOC require 'base64' raise Puppet::ParseError, "base64(): Wrong number of arguments (#{args.length}; must be >= 2)" unless args.length >= 2 actions = ['encode', 'decode'] unless actions.include?(args[0]) raise Puppet::ParseError, "base64(): the first argument must be one of 'encode' or 'decode'" end unless args[1].is_a?(String) raise Puppet::ParseError, 'base64(): the second argument must be a string to base64' end method = ['default', 'strict', 'urlsafe'] chosen_method = if args.length <= 2 'default' else args[2] end unless method.include?(chosen_method) raise Puppet::ParseError, "base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'" end case args[0] when 'encode' case chosen_method when 'default' result = Base64.encode64(args[1]) when 'strict' result = Base64.strict_encode64(args[1]) when 'urlsafe' result = Base64.urlsafe_encode64(args[1]) end when 'decode' case chosen_method when 'default' result = Base64.decode64(args[1]) when 'strict' result = Base64.strict_decode64(args[1]) when 'urlsafe' result = Base64.urlsafe_decode64(args[1]) end end return result end end diff --git a/lib/puppet/parser/functions/basename.rb b/lib/puppet/parser/functions/basename.rb index 4473499..1761821 100644 --- a/lib/puppet/parser/functions/basename.rb +++ b/lib/puppet/parser/functions/basename.rb @@ -1,29 +1,28 @@ # frozen_string_literal: true # # basename.rb # module Puppet::Parser::Functions - newfunction(:basename, :type => :rvalue, :doc => <<-DOC + newfunction(:basename, type: :rvalue, doc: <<-DOC @summary Strips directory (and optional suffix) from a filename @return [String] The stripped filename DOC - ) do |arguments| - + ) 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 : diff --git a/lib/puppet/parser/functions/bool2num.rb b/lib/puppet/parser/functions/bool2num.rb index 4e27d5b..a55e5cc 100644 --- a/lib/puppet/parser/functions/bool2num.rb +++ b/lib/puppet/parser/functions/bool2num.rb @@ -1,45 +1,44 @@ # frozen_string_literal: true # # bool2num.rb # module Puppet::Parser::Functions - newfunction(:bool2num, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/bool2str.rb b/lib/puppet/parser/functions/bool2str.rb index c046f32..03d53d4 100644 --- a/lib/puppet/parser/functions/bool2str.rb +++ b/lib/puppet/parser/functions/bool2str.rb @@ -1,65 +1,64 @@ # frozen_string_literal: true # # bool2str.rb # module Puppet::Parser::Functions - newfunction(:bool2str, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/camelcase.rb b/lib/puppet/parser/functions/camelcase.rb index ddbd1b8..4e6330c 100644 --- a/lib/puppet/parser/functions/camelcase.rb +++ b/lib/puppet/parser/functions/camelcase.rb @@ -1,42 +1,41 @@ # 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 + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/capitalize.rb b/lib/puppet/parser/functions/capitalize.rb index 4a1ae91..fef4493 100644 --- a/lib/puppet/parser/functions/capitalize.rb +++ b/lib/puppet/parser/functions/capitalize.rb @@ -1,41 +1,40 @@ # 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 + 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| - + ) 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 diff --git a/lib/puppet/parser/functions/ceiling.rb b/lib/puppet/parser/functions/ceiling.rb index 1344b3c..b801235 100644 --- a/lib/puppet/parser/functions/ceiling.rb +++ b/lib/puppet/parser/functions/ceiling.rb @@ -1,34 +1,33 @@ # frozen_string_literal: true # # ceiling.rb # module Puppet::Parser::Functions - newfunction(:ceiling, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/chomp.rb b/lib/puppet/parser/functions/chomp.rb index a117001..84aeaf1 100644 --- a/lib/puppet/parser/functions/chomp.rb +++ b/lib/puppet/parser/functions/chomp.rb @@ -1,42 +1,41 @@ # frozen_string_literal: true # # chomp.rb # module Puppet::Parser::Functions - newfunction(:chomp, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/chop.rb b/lib/puppet/parser/functions/chop.rb index f19855e..2e4b054 100644 --- a/lib/puppet/parser/functions/chop.rb +++ b/lib/puppet/parser/functions/chop.rb @@ -1,42 +1,41 @@ # frozen_string_literal: true # # chop.rb # module Puppet::Parser::Functions - newfunction(:chop, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/clamp.rb b/lib/puppet/parser/functions/clamp.rb index df30caa..c056884 100644 --- a/lib/puppet/parser/functions/clamp.rb +++ b/lib/puppet/parser/functions/clamp.rb @@ -1,47 +1,46 @@ # frozen_string_literal: true # # clamp.rb # module Puppet::Parser::Functions - newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-DOC + 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| - + ) 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 value =~ %r{^\d+$} + 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 diff --git a/lib/puppet/parser/functions/concat.rb b/lib/puppet/parser/functions/concat.rb index f5b3eaa..2ee1c2a 100644 --- a/lib/puppet/parser/functions/concat.rb +++ b/lib/puppet/parser/functions/concat.rb @@ -1,49 +1,48 @@ # frozen_string_literal: true # # concat.rb # module Puppet::Parser::Functions - newfunction(:concat, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/convert_base.rb b/lib/puppet/parser/functions/convert_base.rb index d5c1ade..d655419 100644 --- a/lib/puppet/parser/functions/convert_base.rb +++ b/lib/puppet/parser/functions/convert_base.rb @@ -1,53 +1,53 @@ # frozen_string_literal: true # # convert_base.rb # module Puppet::Parser::Functions - newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'DOC') do |args| + 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 args[0] =~ %r{^[0-9]+$} + 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 args[1] =~ %r{^[0-9]+$} + 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 diff --git a/lib/puppet/parser/functions/count.rb b/lib/puppet/parser/functions/count.rb index db42a87..b2bd89a 100644 --- a/lib/puppet/parser/functions/count.rb +++ b/lib/puppet/parser/functions/count.rb @@ -1,43 +1,42 @@ # frozen_string_literal: true # # count.rb # module Puppet::Parser::Functions - newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC + 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| - + ) 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 diff --git a/lib/puppet/parser/functions/deep_merge.rb b/lib/puppet/parser/functions/deep_merge.rb index 2f8768e..bd796ec 100644 --- a/lib/puppet/parser/functions/deep_merge.rb +++ b/lib/puppet/parser/functions/deep_merge.rb @@ -1,53 +1,53 @@ # frozen_string_literal: true # # deep_merge.rb # module Puppet::Parser::Functions - newfunction(:deep_merge, :type => :rvalue, :doc => <<-'DOC') do |args| + 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 diff --git a/lib/puppet/parser/functions/defined_with_params.rb b/lib/puppet/parser/functions/defined_with_params.rb index 0f2c38f..74fc67a 100644 --- a/lib/puppet/parser/functions/defined_with_params.rb +++ b/lib/puppet/parser/functions/defined_with_params.rb @@ -1,81 +1,81 @@ # 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 + 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 diff --git a/lib/puppet/parser/functions/delete.rb b/lib/puppet/parser/functions/delete.rb index 1792397..e66b3c4 100644 --- a/lib/puppet/parser/functions/delete.rb +++ b/lib/puppet/parser/functions/delete.rb @@ -1,69 +1,68 @@ # frozen_string_literal: true # # delete.rb # module Puppet::Parser::Functions - newfunction(:delete, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/delete_at.rb b/lib/puppet/parser/functions/delete_at.rb index 9a884fb..12cba08 100644 --- a/lib/puppet/parser/functions/delete_at.rb +++ b/lib/puppet/parser/functions/delete_at.rb @@ -1,63 +1,63 @@ # frozen_string_literal: true # # delete_at.rb # module Puppet::Parser::Functions - newfunction(:delete_at, :type => :rvalue, :doc => <<-DOC) do |arguments| + 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 : diff --git a/lib/puppet/parser/functions/delete_regex.rb b/lib/puppet/parser/functions/delete_regex.rb index ae13814..0f14177 100644 --- a/lib/puppet/parser/functions/delete_regex.rb +++ b/lib/puppet/parser/functions/delete_regex.rb @@ -1,54 +1,53 @@ # 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 + 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| - + ) 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 : diff --git a/lib/puppet/parser/functions/delete_undef_values.rb b/lib/puppet/parser/functions/delete_undef_values.rb index 39724ab..e537e9a 100644 --- a/lib/puppet/parser/functions/delete_undef_values.rb +++ b/lib/puppet/parser/functions/delete_undef_values.rb @@ -1,44 +1,43 @@ # frozen_string_literal: true # # delete_undef_values.rb # module Puppet::Parser::Functions - newfunction(:delete_undef_values, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 diff --git a/lib/puppet/parser/functions/delete_values.rb b/lib/puppet/parser/functions/delete_values.rb index 6f8c560..3aa8be7 100644 --- a/lib/puppet/parser/functions/delete_values.rb +++ b/lib/puppet/parser/functions/delete_values.rb @@ -1,35 +1,34 @@ # frozen_string_literal: true # # delete_values.rb # module Puppet::Parser::Functions - newfunction(:delete_values, :type => :rvalue, :doc => <<-DOC + 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| - + ) 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 diff --git a/lib/puppet/parser/functions/deprecation.rb b/lib/puppet/parser/functions/deprecation.rb index 98147a9..1633723 100644 --- a/lib/puppet/parser/functions/deprecation.rb +++ b/lib/puppet/parser/functions/deprecation.rb @@ -1,28 +1,27 @@ # frozen_string_literal: true # # deprecation.rb # module Puppet::Parser::Functions - newfunction(:deprecation, :doc => <<-DOC + 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| - + ) 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 diff --git a/lib/puppet/parser/functions/difference.rb b/lib/puppet/parser/functions/difference.rb index 80315f4..3c44610 100644 --- a/lib/puppet/parser/functions/difference.rb +++ b/lib/puppet/parser/functions/difference.rb @@ -1,46 +1,45 @@ # frozen_string_literal: true # # difference.rb # module Puppet::Parser::Functions - newfunction(:difference, :type => :rvalue, :doc => <<-DOC + newfunction(:difference, type: :rvalue, doc: <<-DOC @summary This function returns the difference between two arrays. The returned array is a copy of the original array, removing any items that also appear in the second array. @example Example usage difference(["a","b","c"],["b","c","d"]) Would return: `["a"]` > *Note:* Since Puppet 4 the minus (-) operator in the Puppet language does the same thing: ['a', 'b', 'c'] - ['b', 'c', 'd'] Would return: `['a']` @return [Array] The difference between the two given arrays DOC - ) do |arguments| - + ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "difference(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, 'difference(): Requires 2 arrays') end result = first - second return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/dig.rb b/lib/puppet/parser/functions/dig.rb index 9c63198..81b58e1 100644 --- a/lib/puppet/parser/functions/dig.rb +++ b/lib/puppet/parser/functions/dig.rb @@ -1,59 +1,59 @@ # frozen_string_literal: true # # dig.rb # module Puppet::Parser::Functions - newfunction(:dig, :type => :rvalue, :doc => <<-DOC + newfunction(:dig, type: :rvalue, doc: <<-DOC @summary **DEPRECATED** Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. @return The function goes through the structure by each path component and tries to return the value at the end of the path. In addition to the required path argument, the function accepts the default argument. It is returned if the path is not correct, if no value was found, or if any other error has occurred. ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` 1. `$data` The data structure we are working with. 2. `['a', 'b', 2]` The path array. 3. `not_found` The default value. It is returned if nothing is found. > **Note:* **Deprecated** This function has been replaced with a built-in [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version. DOC - ) do |arguments| + ) do |arguments| warning('dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.') unless Puppet::Parser::Functions.autoloader.loaded?(:dig44) Puppet::Parser::Functions.autoloader.load(:dig44) end function_dig44(arguments) end end diff --git a/lib/puppet/parser/functions/dig44.rb b/lib/puppet/parser/functions/dig44.rb index 04a0980..7b58c22 100644 --- a/lib/puppet/parser/functions/dig44.rb +++ b/lib/puppet/parser/functions/dig44.rb @@ -1,72 +1,72 @@ # frozen_string_literal: true # # dig44.rb # module Puppet::Parser::Functions newfunction( :dig44, - :type => :rvalue, - :arity => -2, - :doc => <<-DOC + type: :rvalue, + arity: -2, + doc: <<-DOC, @summary **DEPRECATED**: Looks up into a complex structure of arrays and hashes and returns a value or the default value if nothing was found. Key can contain slashes to describe path components. The function will go down the structure and try to extract the required value. ``` $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig44($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig44($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` > **Note:* **Deprecated** This function has been replaced with a built-in [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of Puppet 4.5.0. @return [String] 'not_found' will be returned if nothing is found @return [Any] the value that was searched for DOC ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2 data, path, default = *arguments raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") unless data.is_a?(Hash) || data.is_a?(Array) raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") unless path.is_a? Array value = path.reduce(data) do |structure, key| break unless structure.is_a?(Hash) || structure.is_a?(Array) if structure.is_a? Array begin key = Integer key rescue break end end break if structure[key].nil? || structure[key] == :undef structure[key] end value.nil? ? default : value end end diff --git a/lib/puppet/parser/functions/dirname.rb b/lib/puppet/parser/functions/dirname.rb index 5a0eb0f..4a07a29 100644 --- a/lib/puppet/parser/functions/dirname.rb +++ b/lib/puppet/parser/functions/dirname.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # dirname.rb # module Puppet::Parser::Functions - newfunction(:dirname, :type => :rvalue, :doc => <<-DOC + newfunction(:dirname, type: :rvalue, doc: <<-DOC @summary Returns the dirname of a path. @return [String] the given path's dirname DOC - ) do |arguments| - + ) do |arguments| if arguments.empty? raise(Puppet::ParseError, 'dirname(): No arguments given') end if arguments.size > 1 raise(Puppet::ParseError, "dirname(): Too many arguments given (#{arguments.size})") end unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dirname(): Requires string as argument') end # undef is converted to an empty string '' if arguments[0].empty? raise(Puppet::ParseError, 'dirname(): Requires a non-empty string as argument') end return File.dirname(arguments[0]) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/dos2unix.rb b/lib/puppet/parser/functions/dos2unix.rb index 40d0de6..0e2b2b6 100644 --- a/lib/puppet/parser/functions/dos2unix.rb +++ b/lib/puppet/parser/functions/dos2unix.rb @@ -1,21 +1,20 @@ # frozen_string_literal: true # Custom Puppet function to convert dos to unix format module Puppet::Parser::Functions - newfunction(:dos2unix, :type => :rvalue, :arity => 1, :doc => <<-DOC + newfunction(:dos2unix, type: :rvalue, arity: 1, doc: <<-DOC @summary Returns the Unix version of the given string. Takes a single string argument. @return The retrieved version DOC - ) do |arguments| - + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dos2unix(): Requires string as argument') end arguments[0].gsub(%r{\r\n}, "\n") end end diff --git a/lib/puppet/parser/functions/downcase.rb b/lib/puppet/parser/functions/downcase.rb index 677d4dd..32e338c 100644 --- a/lib/puppet/parser/functions/downcase.rb +++ b/lib/puppet/parser/functions/downcase.rb @@ -1,42 +1,41 @@ # frozen_string_literal: true # # downcase.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(:downcase, :type => :rvalue, :doc => <<-DOC + newfunction(:downcase, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Converts the case of a string or all strings in an array to lower case. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`downcase`](https://puppet.com/docs/puppet/latest/function.html#downcase) function. > This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. @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| - + ) do |arguments| raise(Puppet::ParseError, "downcase(): 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, 'downcase(): 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.downcase : i } else value.downcase end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/empty.rb b/lib/puppet/parser/functions/empty.rb index ca15b12..ee1dabc 100644 --- a/lib/puppet/parser/functions/empty.rb +++ b/lib/puppet/parser/functions/empty.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # empty.rb # module Puppet::Parser::Functions - newfunction(:empty, :type => :rvalue, :doc => <<-DOC + newfunction(:empty, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable is empty. @return Returns `true` if the argument is an array or hash that contains no elements, or an empty string. Returns `false` when the argument is a numerical value. > *Note*: **Deprecated** from Puppet 5.5.0, the built-in [`empty`](https://puppet.com/docs/puppet/6.4/function.html#empty) function will be used instead. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "empty(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(String) || value.is_a?(Numeric) raise(Puppet::ParseError, 'empty(): Requires either array, hash, string or integer to work with') end return false if value.is_a?(Numeric) result = value.empty? return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/enclose_ipv6.rb b/lib/puppet/parser/functions/enclose_ipv6.rb index 80ed585..cfa174b 100644 --- a/lib/puppet/parser/functions/enclose_ipv6.rb +++ b/lib/puppet/parser/functions/enclose_ipv6.rb @@ -1,48 +1,47 @@ # frozen_string_literal: true # # enclose_ipv6.rb # module Puppet::Parser::Functions - newfunction(:enclose_ipv6, :type => :rvalue, :doc => <<-DOC + newfunction(:enclose_ipv6, type: :rvalue, doc: <<-DOC @summary Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. @return encloses the ipv6 addresses with square brackets. DOC - ) do |arguments| - + ) do |arguments| require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if arguments.size != 1 raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments given #{arguments.size} for 1") end unless arguments[0].is_a?(String) || arguments[0].is_a?(Array) raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type given #{arguments[0].class} expected String or Array") end input = [arguments[0]].flatten.compact result = [] input.each do |val| unless val == '*' begin ip = IPAddr.new(val) rescue *rescuable_exceptions raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument given #{val} is not an ip address.") end val = "[#{ip}]" if ip.ipv6? end result << val end return result.uniq end end diff --git a/lib/puppet/parser/functions/ensure_packages.rb b/lib/puppet/parser/functions/ensure_packages.rb index b716b18..3cd2b20 100644 --- a/lib/puppet/parser/functions/ensure_packages.rb +++ b/lib/puppet/parser/functions/ensure_packages.rb @@ -1,55 +1,54 @@ # frozen_string_literal: true # # ensure_packages.rb # module Puppet::Parser::Functions - newfunction(:ensure_packages, :type => :statement, :doc => <<-DOC + newfunction(:ensure_packages, type: :statement, doc: <<-DOC @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. @return install the passed packages DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments given (#{arguments.size} for 1 or 2)") if arguments.size > 2 || arguments.empty? raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') if arguments.size == 2 && !arguments[1].is_a?(Hash) if arguments[0].is_a?(Hash) if arguments[1] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resources) function_ensure_resources(['package', arguments[0].dup, defaults]) else packages = Array(arguments[0]) if arguments[1] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resource) packages.each do |package_name| raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.empty? function_ensure_resource(['package', package_name, defaults]) end end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/ensure_resource.rb b/lib/puppet/parser/functions/ensure_resource.rb index 56b3a5d..e606360 100644 --- a/lib/puppet/parser/functions/ensure_resource.rb +++ b/lib/puppet/parser/functions/ensure_resource.rb @@ -1,54 +1,54 @@ # frozen_string_literal: true # Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resource, - :type => :statement, - :doc => <<-DOC + type: :statement, + doc: <<-DOC, @summary Takes a resource type, title, and a list of attributes that describe a resource. user { 'dan': ensure => present, } @return created or recreated the passed resource with the passed type and attributes @example Example usage Creates the resource if it does not already exist: ensure_resource('user', 'dan', {'ensure' => 'present' }) If the resource already exists but does not match the specified parameters, this function will attempt to recreate the resource leading to a duplicate resource definition error. An array of resources can also be passed in and each will be created with the type and parameters specified if it doesn't already exist. ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} items = [title].flatten items.each do |item| Puppet::Parser::Functions.function(:defined_with_params) if function_defined_with_params(["#{type}[#{item}]", params]) Puppet.debug("Resource #{type}[#{item}] with params #{params} not created because it already exists") else Puppet.debug("Create new resource #{type}[#{item}] with params #{params}") Puppet::Parser::Functions.function(:create_resources) function_create_resources([type.capitalize, { item => params }]) end end end diff --git a/lib/puppet/parser/functions/ensure_resources.rb b/lib/puppet/parser/functions/ensure_resources.rb index 3be0ab4..ed82b23 100644 --- a/lib/puppet/parser/functions/ensure_resources.rb +++ b/lib/puppet/parser/functions/ensure_resources.rb @@ -1,58 +1,58 @@ # frozen_string_literal: true require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resources, - :type => :statement, - :doc => <<-DOC + type: :statement, + doc: <<-DOC, @summary Takes a resource type, title (only hash), and a list of attributes that describe a resource. @return created resources with the passed type and attributes @example Example usage user { 'dan': gid => 'mygroup', ensure => present, } An hash of resources should be passed in and each will be created with the type and parameters specified if it doesn't already exist. ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' }, 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) From Hiera Backend: userlist: dan: gid: 'mygroup' uid: '600' alex: gid: 'mygroup' Call: ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} raise(Puppet::ParseError, 'ensure_resources(): Requires second argument to be a Hash') unless title.is_a?(Hash) resource_hash = title.dup resources = resource_hash.keys Puppet::Parser::Functions.function(:ensure_resource) resources.each do |resource_name| params_merged = if resource_hash[resource_name] params.merge(resource_hash[resource_name]) else params end function_ensure_resource([type, resource_name, params_merged]) end end diff --git a/lib/puppet/parser/functions/flatten.rb b/lib/puppet/parser/functions/flatten.rb index 9621fc9..a544d33 100644 --- a/lib/puppet/parser/functions/flatten.rb +++ b/lib/puppet/parser/functions/flatten.rb @@ -1,38 +1,37 @@ # frozen_string_literal: true # # flatten.rb # module Puppet::Parser::Functions - newfunction(:flatten, :type => :rvalue, :doc => <<-DOC + newfunction(:flatten, type: :rvalue, doc: <<-DOC @summary This function flattens any deeply nested arrays and returns a single flat array as a result. @return convert nested arrays into a single flat array @example Example usage flatten(['a', ['b', ['c']]])` returns: `['a','b','c'] > **Note:** **Deprecated** from Puppet 5.5.0, this function has been replaced with a built-in [`flatten`](https://puppet.com/docs/puppet/latest/function.html#flatten) function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "flatten(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'flatten(): Requires array to work with') end result = array.flatten return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/floor.rb b/lib/puppet/parser/functions/floor.rb index 6ea5313..1d59963 100644 --- a/lib/puppet/parser/functions/floor.rb +++ b/lib/puppet/parser/functions/floor.rb @@ -1,34 +1,33 @@ # frozen_string_literal: true # # floor.rb # module Puppet::Parser::Functions - newfunction(:floor, :type => :rvalue, :doc => <<-DOC + newfunction(:floor, type: :rvalue, doc: <<-DOC @summary Returns the largest integer less or equal to the argument. @return the largest integer less 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 [`floor`](https://puppet.com/docs/puppet/latest/function.html#floor) function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "floor(): 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, "floor(): Wrong argument type given (#{arguments[0]} for Numeric)") end raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.floor end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/fqdn_rand_string.rb b/lib/puppet/parser/functions/fqdn_rand_string.rb index 51ff1b8..69041b2 100644 --- a/lib/puppet/parser/functions/fqdn_rand_string.rb +++ b/lib/puppet/parser/functions/fqdn_rand_string.rb @@ -1,45 +1,45 @@ # frozen_string_literal: true Puppet::Parser::Functions.newfunction( :fqdn_rand_string, - :arity => -2, - :type => :rvalue, - :doc => <<-DOC + arity: -2, + type: :rvalue, + doc: <<-DOC, @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). Arguments * An integer, specifying the length of the resulting string. * Optionally, a string specifying the character set. * Optionally, a string specifying 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') DOC ) do |args| raise(ArgumentError, 'fqdn_rand_string(): wrong number of arguments (0 for 1)') if args.empty? Puppet::Parser::Functions.function('is_integer') raise(ArgumentError, 'fqdn_rand_string(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 raise(ArgumentError, 'fqdn_rand_string(): second argument must be undef or a string') unless args[1].nil? || args[1].is_a?(String) Puppet::Parser::Functions.function('fqdn_rand') length = args.shift.to_i charset = args.shift.to_s.chars.to_a charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty? rand_string = '' for current in 1..length # rubocop:disable Style/For : An each loop would not work correctly in this circumstance rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i] end rand_string end diff --git a/lib/puppet/parser/functions/fqdn_rotate.rb b/lib/puppet/parser/functions/fqdn_rotate.rb index 39c98ff..603c57c 100644 --- a/lib/puppet/parser/functions/fqdn_rotate.rb +++ b/lib/puppet/parser/functions/fqdn_rotate.rb @@ -1,65 +1,64 @@ # frozen_string_literal: true # # fqdn_rotate.rb # Puppet::Parser::Functions.newfunction( :fqdn_rotate, - :type => :rvalue, - :doc => <<-DOC + type: :rvalue, + doc: <<-DOC, @summary Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness. @return rotated array or string @example Example Usage: fqdn_rotate(['a', 'b', 'c', 'd']) fqdn_rotate('abcd') fqdn_rotate([1, 2, 3], 'custom seed') DOC ) do |args| - raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.empty? value = args.shift require 'digest/md5' unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to rotate ... return result if result.size <= 1 # We turn any string value into an array to be able to rotate ... result = string ? result.split('') : result elements = result.size seed = Digest::MD5.hexdigest([lookupvar('::fqdn'), args].join(':')).hex # deterministic_rand() was added in Puppet 3.2.0; reimplement if necessary if Puppet::Util.respond_to?(:deterministic_rand) offset = Puppet::Util.deterministic_rand(seed, elements).to_i else return offset = Random.new(seed).rand(elements) if defined?(Random) == 'constant' && Random.class == Class old_seed = srand(seed) offset = rand(elements) srand(old_seed) end offset.times do result.push result.shift end result = string ? result.join : result return result end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/fqdn_uuid.rb b/lib/puppet/parser/functions/fqdn_uuid.rb index 73d38ce..b3141c8 100644 --- a/lib/puppet/parser/functions/fqdn_uuid.rb +++ b/lib/puppet/parser/functions/fqdn_uuid.rb @@ -1,70 +1,70 @@ # frozen_string_literal: true require 'digest/sha1' # # fqdn_uuid.rb # module Puppet::Parser::Functions - newfunction(:fqdn_uuid, :type => :rvalue, :doc => <<-DOC) do |args| + newfunction(:fqdn_uuid, type: :rvalue, doc: <<-DOC) do |args| @summary Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace @return Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID @example Example Usage: fqdn_uuid('puppetlabs.com') # Returns '9c70320f-6815-5fc5-ab0f-debe68bf764c' fqdn_uuid('google.com') # Returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8' DOC raise(ArgumentError, 'fqdn_uuid: No arguments given') if args.empty? raise(ArgumentError, "fqdn_uuid: Too many arguments given (#{args.length})") unless args.length == 1 fqdn = args[0] # Code lovingly taken from # https://github.com/puppetlabs/marionette-collective/blob/master/lib/mcollective/ssl.rb # This is the UUID version 5 type DNS name space which is as follows: # # 6ba7b810-9dad-11d1-80b4-00c04fd430c8 # uuid_name_space_dns = [0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8].map { |b| b.chr }.join sha1 = Digest::SHA1.new sha1.update(uuid_name_space_dns) sha1.update(fqdn) # first 16 bytes.. bytes = sha1.digest[0, 16].bytes.to_a # version 5 adjustments bytes[6] &= 0x0f bytes[6] |= 0x50 # variant is DCE 1.1 bytes[8] &= 0x3f bytes[8] |= 0x80 bytes = [4, 2, 2, 2, 6].map do |i| bytes.slice!(0, i).pack('C*').unpack('H*') end bytes.join('-') end end diff --git a/lib/puppet/parser/functions/get_module_path.rb b/lib/puppet/parser/functions/get_module_path.rb index 19f2a4e..3595d53 100644 --- a/lib/puppet/parser/functions/get_module_path.rb +++ b/lib/puppet/parser/functions/get_module_path.rb @@ -1,31 +1,31 @@ # frozen_string_literal: true # # get_module_path.rb # module Puppet::Parser::Functions - newfunction(:get_module_path, :type => :rvalue, :doc => <<-DOC + newfunction(:get_module_path, type: :rvalue, doc: <<-DOC @summary Returns the absolute path of the specified module for the current environment. @return Returns the absolute path of the specified module for the current environment. @example Example Usage: $module_path = get_module_path('stdlib') > *Note:* that since Puppet 5.4.0 the built-in [`module_directory`](https://puppet.com/docs/puppet/latest/function.html#module_directory) function in Puppet does the same thing and will return the path to the first found module if given multiple values or an array. DOC - ) do |args| + ) do |args| raise(Puppet::ParseError, 'get_module_path(): Wrong number of arguments, expects one') unless args.size == 1 module_path = Puppet::Module.find(args[0], compiler.environment.to_s) raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") unless module_path module_path.path end end diff --git a/lib/puppet/parser/functions/getparam.rb b/lib/puppet/parser/functions/getparam.rb index f734d51..b666710 100644 --- a/lib/puppet/parser/functions/getparam.rb +++ b/lib/puppet/parser/functions/getparam.rb @@ -1,61 +1,61 @@ # frozen_string_literal: true # Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:getparam, - :type => :rvalue, - :doc => <<-'DOC' + type: :rvalue, + doc: <<-'DOC', @summary Returns the value of a resource's parameter. @return value of a resource's parameter. Takes a resource reference and name of the parameter and returns value of resource's parameter. Note that user defined resource types are evaluated lazily. @example Example Usage: # define a resource type with a parameter define example_resource($param) { } # declare an instance of that type example_resource { "example_resource_instance": param => "'the value we are getting in this example''" } # Because of order of evaluation, a second definition is needed # that will be evaluated after the first resource has been declared # define example_get_param { # This will notice the value of the parameter notice(getparam(Example_resource["example_resource_instance"], "param")) } # Declare an instance of the second resource type - this will call notice example_get_param { 'show_notify': } Would notice: 'the value we are getting in this example' > **Note** that since Puppet 4.0.0 it is possible to get a parameter value by using its data type and the [ ] operator. The example below is equivalent to a call to getparam(): ```Example_resource['example_resource_instance']['param']`` DOC ) do |vals| reference, param = vals raise(ArgumentError, 'Must specify a reference') unless reference raise(ArgumentError, 'Must specify name of a parameter') unless param && param.instance_of?(String) return '' if param.empty? resource = findresource(reference.to_s) if resource return resource[param] unless resource[param].nil? end return '' end diff --git a/lib/puppet/parser/functions/getvar.rb b/lib/puppet/parser/functions/getvar.rb index 6bcf243..4ecd832 100644 --- a/lib/puppet/parser/functions/getvar.rb +++ b/lib/puppet/parser/functions/getvar.rb @@ -1,42 +1,42 @@ # frozen_string_literal: true # # getvar.rb # module Puppet::Parser::Functions - newfunction(:getvar, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:getvar, type: :rvalue, doc: <<-'DOC') do |args| @summary Lookup a variable in a given namespace. @return undef - if variable does not exist @example Example usage $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo @example Where namespace is stored in a string $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar > **Note:** from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. The new function also has support for digging into a structured value. See the built-in [`getvar`](https://puppet.com/docs/puppet/latest/function.html#getvar) function DOC unless args.length == 1 raise Puppet::ParseError, "getvar(): wrong number of arguments (#{args.length}; must be 1)" end begin result = nil catch(:undefined_variable) do result = lookupvar((args[0]).to_s) end # avoid relying on inconsistent behaviour around ruby return values from catch result - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end end end diff --git a/lib/puppet/parser/functions/glob.rb b/lib/puppet/parser/functions/glob.rb index 49737e6..be4e0d2 100644 --- a/lib/puppet/parser/functions/glob.rb +++ b/lib/puppet/parser/functions/glob.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # glob.rb # module Puppet::Parser::Functions - newfunction(:glob, :type => :rvalue, :doc => <<-DOC + newfunction(:glob, type: :rvalue, doc: <<-DOC @summary Uses same patterns as Dir#glob. @return Returns an Array of file entries of a directory or an Array of directories. @example Example Usage: $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf']) DOC - ) do |arguments| - + ) do |arguments| unless arguments.size == 1 raise(Puppet::ParseError, 'glob(): Wrong number of arguments given ' \ "(#{arguments.size} for 1)") end pattern = arguments[0] unless pattern.is_a?(String) || pattern.is_a?(Array) raise(Puppet::ParseError, 'glob(): Requires either array or string ' \ 'to work') end Dir.glob(pattern) end end diff --git a/lib/puppet/parser/functions/grep.rb b/lib/puppet/parser/functions/grep.rb index a05d0d4..6ef3ee4 100644 --- a/lib/puppet/parser/functions/grep.rb +++ b/lib/puppet/parser/functions/grep.rb @@ -1,35 +1,34 @@ # frozen_string_literal: true # # grep.rb # module Puppet::Parser::Functions - newfunction(:grep, :type => :rvalue, :doc => <<-DOC + newfunction(:grep, type: :rvalue, doc: <<-DOC @summary This function searches through an array and returns any elements that match the provided regular expression. @return array of elements that match the provided regular expression. @example Example Usage: grep(['aaa','bbb','ccc','aaaddd'], 'aaa') # Returns ['aaa','aaaddd'] > **Note:** that since Puppet 4.0.0, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function does the "same" - as any logic can be used to filter, as opposed to just regular expressions: ```['aaa', 'bbb', 'ccc', 'aaaddd']. filter |$x| { $x =~ 'aaa' }``` DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 2 raise(Puppet::ParseError, "grep(): Wrong number of arguments given #{arguments.size} for 2") end a = arguments[0] pattern = Regexp.new(arguments[1]) a.grep(pattern) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/has_interface_with.rb b/lib/puppet/parser/functions/has_interface_with.rb index 9fc80fc..0404217 100644 --- a/lib/puppet/parser/functions/has_interface_with.rb +++ b/lib/puppet/parser/functions/has_interface_with.rb @@ -1,73 +1,72 @@ # frozen_string_literal: true # # has_interface_with # module Puppet::Parser::Functions - newfunction(:has_interface_with, :type => :rvalue, :doc => <<-DOC + newfunction(:has_interface_with, type: :rvalue, doc: <<-DOC @summary Returns boolean based on kind and value. @return boolean values `true` or `false` Valid kinds are `macaddress`, `netmask`, `ipaddress` and `network`. @example **Usage** has_interface_with("macaddress", "x:x:x:x:x:x") # Returns `false` has_interface_with("ipaddress", "127.0.0.1") # Returns `true` @example If no "kind" is given, then the presence of the interface is checked: has_interface_with("lo") # Returns `true` DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments given (#{args.size} for 1 or 2)") if args.empty? || args.size > 2 interfaces = lookupvar('interfaces') # If we do not have any interfaces, then there are no requested attributes return false if interfaces == :undefined || interfaces.nil? interfaces = interfaces.split(',') if args.size == 1 return interfaces.member?(args[0]) end kind, value = args # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 factval = nil begin catch :undefined_variable do factval = lookupvar(kind) end - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end if factval == value return true end result = false interfaces.each do |iface| iface.downcase! factval = nil begin # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 catch :undefined_variable do factval = lookupvar("#{kind}_#{iface}") end - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end if value == factval result = true break end end result end end diff --git a/lib/puppet/parser/functions/has_ip_address.rb b/lib/puppet/parser/functions/has_ip_address.rb index ceaadf9..0cea4a7 100644 --- a/lib/puppet/parser/functions/has_ip_address.rb +++ b/lib/puppet/parser/functions/has_ip_address.rb @@ -1,28 +1,27 @@ # frozen_string_literal: true # # has_ip_address # module Puppet::Parser::Functions - newfunction(:has_ip_address, :type => :rvalue, :doc => <<-DOC + newfunction(:has_ip_address, type: :rvalue, doc: <<-DOC @summary Returns true if the client has the requested IP address on some interface. @return [Boolean] `true` or `false` This function iterates through the 'interfaces' fact and checks the 'ipaddress_IFACE' facts, performing a simple string comparison. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['ipaddress', args[0]]) end end # vim:sts=2 sw=2 diff --git a/lib/puppet/parser/functions/has_ip_network.rb b/lib/puppet/parser/functions/has_ip_network.rb index 8dc78f5..7406ed5 100644 --- a/lib/puppet/parser/functions/has_ip_network.rb +++ b/lib/puppet/parser/functions/has_ip_network.rb @@ -1,28 +1,27 @@ # frozen_string_literal: true # # has_ip_network # module Puppet::Parser::Functions - newfunction(:has_ip_network, :type => :rvalue, :doc => <<-DOC + newfunction(:has_ip_network, type: :rvalue, doc: <<-DOC @summary Returns true if the client has an IP address within the requested network. @return Boolean value, `true` if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['network', args[0]]) end end # vim:sts=2 sw=2 diff --git a/lib/puppet/parser/functions/has_key.rb b/lib/puppet/parser/functions/has_key.rb index 7a0d373..334b849 100644 --- a/lib/puppet/parser/functions/has_key.rb +++ b/lib/puppet/parser/functions/has_key.rb @@ -1,41 +1,41 @@ # frozen_string_literal: true # # has_key.rb # module Puppet::Parser::Functions - newfunction(:has_key, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:has_key, type: :rvalue, doc: <<-'DOC') do |args| @summary **Deprecated:** Determine if a hash has a certain key value. @return Boolean value @example Example Usage: $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } > **Note:** **Deprecated** since Puppet 4.0.0, this can now be achieved in the Puppet language with the following equivalent expression: $my_hash = {'key_one' => 'value_one'} if 'key_one' in $my_hash { notice('this will be printed') } DOC unless args.length == 2 raise Puppet::ParseError, "has_key(): wrong number of arguments (#{args.length}; must be 2)" end unless args[0].is_a?(Hash) raise Puppet::ParseError, "has_key(): expects the first argument to be a hash, got #{args[0].inspect} which is of type #{args[0].class}" end args[0].key?(args[1]) end end diff --git a/lib/puppet/parser/functions/hash.rb b/lib/puppet/parser/functions/hash.rb index 7dfae9d..029089e 100644 --- a/lib/puppet/parser/functions/hash.rb +++ b/lib/puppet/parser/functions/hash.rb @@ -1,49 +1,48 @@ # frozen_string_literal: true # # hash.rb # module Puppet::Parser::Functions - newfunction(:hash, :type => :rvalue, :doc => <<-DOC + newfunction(:hash, type: :rvalue, doc: <<-DOC @summary **Deprecated:** This function converts an array into a hash. @return the converted array as a hash @example Example Usage: hash(['a',1,'b',2,'c',3]) # Returns: {'a'=>1,'b'=>2,'c'=>3} > **Note:** This function has been replaced with the built-in ability to create a new value of almost any data type - see the built-in [`Hash.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-hash-and-struct) function in Puppet. This example shows the equivalent expression in the Puppet language: ``` Hash(['a',1,'b',2,'c',3]) Hash([['a',1],['b',2],['c',3]]) ``` DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'hash(): Requires array to work with') end result = {} begin # This is to make it compatible with older version of Ruby ... array = array.flatten result = Hash[*array] rescue StandardError raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given') end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/intersection.rb b/lib/puppet/parser/functions/intersection.rb index 7d8a5c0..ead7580 100644 --- a/lib/puppet/parser/functions/intersection.rb +++ b/lib/puppet/parser/functions/intersection.rb @@ -1,36 +1,35 @@ # frozen_string_literal: true # # intersection.rb # module Puppet::Parser::Functions - newfunction(:intersection, :type => :rvalue, :doc => <<-DOC + newfunction(:intersection, type: :rvalue, doc: <<-DOC @summary This function returns an array of the intersection of two. @return an array of the intersection of two. @example Example Usage: intersection(["a","b","c"],["b","c","d"]) # returns ["b","c"] intersection(["a","b","c"],[1,2,3,4]) # returns [] (true, when evaluated as a Boolean) DOC - ) do |arguments| - + ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "intersection(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, "intersection(): Requires 2 arrays, got #{first.class} and #{second.class}") end result = first & second return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_absolute_path.rb b/lib/puppet/parser/functions/is_absolute_path.rb index 150a8a4..c464afa 100644 --- a/lib/puppet/parser/functions/is_absolute_path.rb +++ b/lib/puppet/parser/functions/is_absolute_path.rb @@ -1,61 +1,61 @@ # frozen_string_literal: true # # is_absolute_path.rb # module Puppet::Parser::Functions - newfunction(:is_absolute_path, :type => :rvalue, :arity => 1, :doc => <<-'DOC') do |args| + newfunction(:is_absolute_path, type: :rvalue, arity: 1, doc: <<-'DOC') do |args| @summary **Deprecated:** Returns boolean true if the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @example The following values will return true: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' is_absolute_path($my_path) $my_path2 = '/var/lib/puppet' is_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet'] is_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet'] is_absolute_path($my_path4) @example The following values will return false: is_absolute_path(true) is_absolute_path('../var/lib/puppet') is_absolute_path('var/lib/puppet') $undefined = undef is_absolute_path($undefined) @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC function_deprecation([:is_absolute_path, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_path. There is further documentation for validate_legacy function in the README.']) require 'puppet/util' path = args[0] # This logic was borrowed from # [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/main/lib/puppet/file_serving/base.rb) # Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise. if Puppet::Util.respond_to?(:absolute_path?) value = (Puppet::Util.absolute_path?(path, :posix) || Puppet::Util.absolute_path?(path, :windows)) else # This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? # Determine in a platform-specific way whether a path is absolute. This # defaults to the local platform if none is specified. # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' name = '[^\\\\/]+' regexes = { - :windows => %r{^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))}i, - :posix => %r{^/}, + windows: %r{^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))}i, + posix: %r{^/}, } value = !!(path =~ regexes[:posix]) || !!(path =~ regexes[:windows]) # rubocop:disable Style/DoubleNegation : No alternative known end value end end diff --git a/lib/puppet/parser/functions/is_array.rb b/lib/puppet/parser/functions/is_array.rb index 890f53b..e4e7b81 100644 --- a/lib/puppet/parser/functions/is_array.rb +++ b/lib/puppet/parser/functions/is_array.rb @@ -1,30 +1,29 @@ # frozen_string_literal: true # # is_array.rb # module Puppet::Parser::Functions - newfunction(:is_array, :type => :rvalue, :doc => <<-DOC + newfunction(:is_array, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is an array. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] result = type.is_a?(Array) return result end end diff --git a/lib/puppet/parser/functions/is_bool.rb b/lib/puppet/parser/functions/is_bool.rb index 5a74770..96cb217 100644 --- a/lib/puppet/parser/functions/is_bool.rb +++ b/lib/puppet/parser/functions/is_bool.rb @@ -1,30 +1,29 @@ # frozen_string_literal: true # # is_bool.rb # module Puppet::Parser::Functions - newfunction(:is_bool, :type => :rvalue, :doc => <<-DOC + newfunction(:is_bool, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a boolean. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_bool, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(TrueClass) || type.is_a?(FalseClass) return result end end diff --git a/lib/puppet/parser/functions/is_domain_name.rb b/lib/puppet/parser/functions/is_domain_name.rb index 2427362..32b9481 100644 --- a/lib/puppet/parser/functions/is_domain_name.rb +++ b/lib/puppet/parser/functions/is_domain_name.rb @@ -1,61 +1,60 @@ # frozen_string_literal: true # # is_domain_name.rb # module Puppet::Parser::Functions - newfunction(:is_domain_name, :type => :rvalue, :doc => <<-DOC + newfunction(:is_domain_name, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a syntactically correct domain name. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow string types return false unless arguments[0].is_a?(String) domain = arguments[0].dup # Limits (rfc1035, 3.1) domain_max_length = 255 label_min_length = 1 label_max_length = 63 # Allow ".", it is the top level domain return true if domain == '.' # Remove the final dot, if present. domain.chomp!('.') # Check the whole domain return false if domain.empty? return false if domain.length > domain_max_length # The top level domain must be alphabetic if there are multiple labels. # See rfc1123, 2.1 return false if domain.include?('.') && !%r{\.[A-Za-z]+$}.match(domain) # Check each label in the domain labels = domain.split('.') vlabels = labels.each do |label| break if label.length < label_min_length break if label.length > label_max_length break if label[-1..-1] == '-' break if label[0..0] == '-' - break unless %r{^[a-z\d-]+$}i =~ label + break unless %r{^[a-z\d-]+$}i.match?(label) end return vlabels == labels end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_email_address.rb b/lib/puppet/parser/functions/is_email_address.rb index 4d5996d..5a9594c 100644 --- a/lib/puppet/parser/functions/is_email_address.rb +++ b/lib/puppet/parser/functions/is_email_address.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true # # is_email_address.rb # module Puppet::Parser::Functions - newfunction(:is_email_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_email_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid email address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_email_address(): Wrong number of arguments given #{arguments.size} for 1") end # Taken from http://emailregex.com/ (simpler regex) valid_email_regex = %r{\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z} - return (arguments[0] =~ valid_email_regex) == 0 # rubocop:disable Style/NumericPredicate : Changing to '.zero?' breaks the code + return (arguments[0] =~ valid_email_regex) == 0 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_float.rb b/lib/puppet/parser/functions/is_float.rb index a0ff06b..c44746b 100644 --- a/lib/puppet/parser/functions/is_float.rb +++ b/lib/puppet/parser/functions/is_float.rb @@ -1,36 +1,35 @@ # frozen_string_literal: true # # is_float.rb # module Puppet::Parser::Functions - newfunction(:is_float, :type => :rvalue, :doc => <<-DOC + newfunction(:is_float, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a float. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_float, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Float. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_float(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Only allow Numeric or String types return false unless value.is_a?(Numeric) || value.is_a?(String) return false if value != value.to_f.to_s && !value.is_a?(Float) return true end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_function_available.rb b/lib/puppet/parser/functions/is_function_available.rb index 081aadc..d6f666f 100644 --- a/lib/puppet/parser/functions/is_function_available.rb +++ b/lib/puppet/parser/functions/is_function_available.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # is_function_available.rb # module Puppet::Parser::Functions - newfunction(:is_function_available, :type => :rvalue, :doc => <<-DOC + newfunction(:is_function_available, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Determines whether the Puppet runtime has access to a function by that name. This function accepts a string as an argument. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow String types return false unless arguments[0].is_a?(String) function = Puppet::Parser::Functions.function(arguments[0].to_sym) function.is_a?(String) && !function.empty? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_hash.rb b/lib/puppet/parser/functions/is_hash.rb index 1cea33a..812ff88 100644 --- a/lib/puppet/parser/functions/is_hash.rb +++ b/lib/puppet/parser/functions/is_hash.rb @@ -1,29 +1,28 @@ # frozen_string_literal: true # # is_hash.rb # module Puppet::Parser::Functions - newfunction(:is_hash, :type => :rvalue, :doc => <<-DOC + newfunction(:is_hash, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a hash. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "is_hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(Hash) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_integer.rb b/lib/puppet/parser/functions/is_integer.rb index 86cdd39..cdb5771 100644 --- a/lib/puppet/parser/functions/is_integer.rb +++ b/lib/puppet/parser/functions/is_integer.rb @@ -1,53 +1,52 @@ # frozen_string_literal: true # # is_integer.rb # module Puppet::Parser::Functions - newfunction(:is_integer, :type => :rvalue, :doc => <<-DOC + newfunction(:is_integer, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is an Integer or a decimal (base 10) integer in String form. The string may start with a '-' (minus). A value of '0' is allowed, but a leading '0' digit may not be followed by other digits as this indicates that the value is octal (base 8). If given any other argument `false` is returned. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_integer(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow numbers prefixed with multiple # 0's # # TODO these parameter should be a constant but I'm not sure # if there is no risk to declare it inside of the module # Puppet::Parser::Functions # Integer numbers like # -1234568981273 # 47291 numeric = %r{^-?(?:(?:[1-9]\d*)|0)$} return true if value.is_a?(Integer) || (value.is_a?(String) && value.match(numeric)) return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ip_address.rb b/lib/puppet/parser/functions/is_ip_address.rb index 1c7b258..506244f 100644 --- a/lib/puppet/parser/functions/is_ip_address.rb +++ b/lib/puppet/parser/functions/is_ip_address.rb @@ -1,39 +1,38 @@ # frozen_string_literal: true # # is_ip_address.rb # module Puppet::Parser::Functions - newfunction(:is_ip_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ip_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IP address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| require 'ipaddr' function_deprecation([:is_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return true if ip.ipv4? || ip.ipv6? return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ipv4_address.rb b/lib/puppet/parser/functions/is_ipv4_address.rb index 405438a..4610805 100644 --- a/lib/puppet/parser/functions/is_ipv4_address.rb +++ b/lib/puppet/parser/functions/is_ipv4_address.rb @@ -1,38 +1,37 @@ # frozen_string_literal: true # # is_ipv4_address.rb # module Puppet::Parser::Functions - newfunction(:is_ipv4_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ipv4_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IPv4 address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| require 'ipaddr' function_deprecation([:is_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv4? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ipv6_address.rb b/lib/puppet/parser/functions/is_ipv6_address.rb index 18bef81..abb79df 100644 --- a/lib/puppet/parser/functions/is_ipv6_address.rb +++ b/lib/puppet/parser/functions/is_ipv6_address.rb @@ -1,38 +1,37 @@ # frozen_string_literal: true # # is_ipv6_address.rb # module Puppet::Parser::Functions - newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ipv6_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IPv6 address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' if arguments.size != 1 raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv6? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_mac_address.rb b/lib/puppet/parser/functions/is_mac_address.rb index 18d4e62..67a269c 100644 --- a/lib/puppet/parser/functions/is_mac_address.rb +++ b/lib/puppet/parser/functions/is_mac_address.rb @@ -1,31 +1,30 @@ # frozen_string_literal: true # # is_mac_address.rb # module Puppet::Parser::Functions - newfunction(:is_mac_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_mac_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid mac address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments given #{arguments.size} for 1") end mac = arguments[0] - return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i =~ mac - return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){19}$}i =~ mac + return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i.match?(mac) + return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){19}$}i.match?(mac) return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_numeric.rb b/lib/puppet/parser/functions/is_numeric.rb index ba889a4..a949557 100644 --- a/lib/puppet/parser/functions/is_numeric.rb +++ b/lib/puppet/parser/functions/is_numeric.rb @@ -1,77 +1,76 @@ # frozen_string_literal: true # # is_numeric.rb # module Puppet::Parser::Functions - newfunction(:is_numeric, :type => :rvalue, :doc => <<-DOC + newfunction(:is_numeric, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the given value is numeric. Returns true if the given argument is a Numeric (Integer or Float), or a String containing either a valid integer in decimal base 10 form, or a valid floating point string representation. The function recognizes only decimal (base 10) integers and float but not integers in hex (base 16) or octal (base 8) form. The string representation may start with a '-' (minus). If a decimal '.' is used, it must be followed by at least one digit. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow invalid octal numbers or # numbers prefixed with multiple 0's (except in hex numbers) # # TODO these parameters should be constants but I'm not sure # if there is no risk to declare them inside of the module # Puppet::Parser::Functions # TODO: decide if this should be used # HEX numbers like # 0xaa230F # 0X1234009C # 0x0012 # -12FcD # numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} # TODO: decide if this should be used # OCTAL numbers like # 01234567 # -045372 # numeric_oct = %r{^-?0[1-7][0-7]*$} # Integer/Float numbers like # -0.1234568981273 # 47291 # 42.12345e-12 numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$} if value.is_a?(Numeric) || (value.is_a?(String) && value.match(numeric) # or # value.match(numeric_hex) or # value.match(numeric_oct) ) return true else return false end end end diff --git a/lib/puppet/parser/functions/is_string.rb b/lib/puppet/parser/functions/is_string.rb index 31b4abd..5b4627a 100644 --- a/lib/puppet/parser/functions/is_string.rb +++ b/lib/puppet/parser/functions/is_string.rb @@ -1,37 +1,36 @@ # frozen_string_literal: true # # is_string.rb # module Puppet::Parser::Functions - newfunction(:is_string, :type => :rvalue, :doc => <<-DOC + newfunction(:is_string, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a string. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| function_deprecation([:is_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_string(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] # when called through the v4 API shim, undef gets translated to nil result = type.is_a?(String) || type.nil? if result && (type == type.to_f.to_s || type == type.to_i.to_s) return false end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/join.rb b/lib/puppet/parser/functions/join.rb index f071fc7..f1e4bc1 100644 --- a/lib/puppet/parser/functions/join.rb +++ b/lib/puppet/parser/functions/join.rb @@ -1,45 +1,44 @@ # frozen_string_literal: true # # join.rb # module Puppet::Parser::Functions - newfunction(:join, :type => :rvalue, :doc => <<-DOC + newfunction(:join, type: :rvalue, doc: <<-DOC @summary **Deprecated:** This function joins an array into a string using a separator. @example Example Usage: join(['a','b','c'], ",") # Results in: "a,b,c" @return [String] The String containing each of the array values > **Note:** **Deprecated** from Puppet 5.4.0 this function has been replaced with a built-in [`join`](https://puppet.com/docs/puppet/latest/function.html#join) function. DOC - ) do |arguments| - + ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'join(): Requires array to work with') end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a?(String) raise(Puppet::ParseError, 'join(): Requires string to work with') end end result = suffix ? array.join(suffix) : array.join return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/join_keys_to_values.rb b/lib/puppet/parser/functions/join_keys_to_values.rb index cc35ad0..3e709cb 100644 --- a/lib/puppet/parser/functions/join_keys_to_values.rb +++ b/lib/puppet/parser/functions/join_keys_to_values.rb @@ -1,60 +1,59 @@ # frozen_string_literal: true # # join_keys_to_values.rb # module Puppet::Parser::Functions - newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-DOC + newfunction(:join_keys_to_values, type: :rvalue, doc: <<-DOC @summary This function joins each key of a hash to that key's corresponding value with a separator. Keys are cast to strings. If values are arrays, multiple keys are added for each element. The return value is an array in which each element is one joined key/value pair. @example Example Usage: join_keys_to_values({'a'=>1,'b'=>2}, " is ") # Results in: ["a is 1","b is 2"] join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") # Results in: ["a is 1","b is 2","b is 3"] @return [Hash] The joined hash > **Note:** Since Puppet 5.0.0 - for more detailed control over the formatting (including indentations and line breaks, delimiters around arrays and hash entries, between key/values in hash entries, and individual formatting of values in the array) - see the `new` function for `String` and its formatting options for `Array` and `Hash`. DOC - ) do |arguments| - + ) do |arguments| # Validate the number of arguments. if arguments.size != 2 raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.") end # Validate the first argument. hash = arguments[0] unless hash.is_a?(Hash) raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.") end # Validate the second argument. separator = arguments[1] unless separator.is_a?(String) raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.") end # Join the keys to their values. hash.map { |k, v| if v.is_a?(Array) v.map { |va| String(k) + separator + String(va) } elsif String(v) == 'undef' String(k) else String(k) + separator + String(v) end }.flatten end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/keys.rb b/lib/puppet/parser/functions/keys.rb index 9fae285..10a8547 100644 --- a/lib/puppet/parser/functions/keys.rb +++ b/lib/puppet/parser/functions/keys.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # keys.rb # module Puppet::Parser::Functions - newfunction(:keys, :type => :rvalue, :doc => <<-DOC + newfunction(:keys, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the keys of a hash as an array. @return [Array] An array containing each of the hashes key values. > **Note:** **Deprecated** from Puppet 5.5.0, the built-in [`keys`](https://puppet.com/docs/puppet/latest/function.html#keys) function will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'keys(): Requires hash to work with') end result = hash.keys return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/load_module_metadata.rb b/lib/puppet/parser/functions/load_module_metadata.rb index 0379778..b1fd196 100644 --- a/lib/puppet/parser/functions/load_module_metadata.rb +++ b/lib/puppet/parser/functions/load_module_metadata.rb @@ -1,35 +1,35 @@ # frozen_string_literal: true # # load_module_metadata.rb # module Puppet::Parser::Functions - newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-DOC + newfunction(:load_module_metadata, type: :rvalue, doc: <<-DOC @summary This function loads the metadata of a given module. @example Example USage: $metadata = load_module_metadata('archive') notify { $metadata['author']: } @return The modules metadata DOC - ) do |args| + ) do |args| raise(Puppet::ParseError, 'load_module_metadata(): Wrong number of arguments, expects one or two') unless [1, 2].include?(args.size) mod = args[0] allow_empty_metadata = args[1] module_path = function_get_module_path([mod]) metadata_json = File.join(module_path, 'metadata.json') metadata_exists = File.exists?(metadata_json) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code if metadata_exists metadata = PSON.load(File.read(metadata_json)) else metadata = {} raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}") unless allow_empty_metadata end return metadata end end diff --git a/lib/puppet/parser/functions/loadjson.rb b/lib/puppet/parser/functions/loadjson.rb index 7ebdaf6..ef1fd87 100644 --- a/lib/puppet/parser/functions/loadjson.rb +++ b/lib/puppet/parser/functions/loadjson.rb @@ -1,64 +1,64 @@ # frozen_string_literal: true # # loadjson.rb # module Puppet::Parser::Functions - newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| + newfunction(:loadjson, type: :rvalue, arity: -2, doc: <<-'DOC') do |args| @summary Load a JSON file containing an array, string, or hash, and return the data in the corresponding native data type. The first parameter can be a file path or a URL. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. @return [Array|String|Hash] The data stored in the JSON file, the type depending on the type of data that was stored. @example Example Usage: $myhash = loadjson('/etc/puppet/data/myhash.json') $myhash = loadjson('https://example.local/my_hash.json') $myhash = loadjson('https://username:password@example.local/my_hash.json') $myhash = loadjson('no-file.json', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'open-uri' begin if args[0].start_with?('http://', 'https://') username = '' password = '' if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)})) # If URL is in the format of https://username:password@example.local/my_hash.yaml protocol, username, password, path = match.captures url = "#{protocol}#{path}" elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)})) # If URL is in the format of https://username@example.local/my_hash.yaml protocol, username, path = match.captures url = "#{protocol}#{path}" else url = args[0] end begin - contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password]) + contents = OpenURI.open_uri(url, http_basic_authentication: [username, password]) rescue OpenURI::HTTPError => err res = err.io warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'") args[1] end PSON.load(contents) || args[1] elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code content = File.read(args[0]) PSON.load(content) || args[1] else warning("Can't load '#{args[0]}' File does not exist!") args[1] end rescue StandardError => e raise e unless args[1] args[1] end end end diff --git a/lib/puppet/parser/functions/loadyaml.rb b/lib/puppet/parser/functions/loadyaml.rb index c33a69b..70f8e5f 100644 --- a/lib/puppet/parser/functions/loadyaml.rb +++ b/lib/puppet/parser/functions/loadyaml.rb @@ -1,63 +1,63 @@ # frozen_string_literal: true # # loadyaml.rb # module Puppet::Parser::Functions - newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| + newfunction(:loadyaml, type: :rvalue, arity: -2, doc: <<-'DOC') do |args| @summary Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. The first parameter can be a file path or a URL. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. @return [Array|String|Hash] The data stored in the YAML file, the type depending on the type of data that was stored. @example Example Usage: $myhash = loadyaml('/etc/puppet/data/myhash.yaml') $myhash = loadyaml('https://example.local/my_hash.yaml') $myhash = loadyaml('https://username:password@example.local/my_hash.yaml') $myhash = loadyaml('no-file.yaml', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'yaml' require 'open-uri' begin if args[0].start_with?('http://', 'https://') username = '' password = '' if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)})) # If URL is in the format of https://username:password@example.local/my_hash.yaml protocol, username, password, path = match.captures url = "#{protocol}#{path}" elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)})) # If URL is in the format of https://username@example.local/my_hash.yaml protocol, username, path = match.captures url = "#{protocol}#{path}" else url = args[0] end begin - contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password]) + contents = OpenURI.open_uri(url, http_basic_authentication: [username, password]) rescue OpenURI::HTTPError => err res = err.io warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'") args[1] end YAML.safe_load(contents) || args[1] elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code YAML.load_file(args[0]) || args[1] else warning("Can't load '#{args[0]}' File does not exist!") args[1] end rescue StandardError => e raise e unless args[1] args[1] end end end diff --git a/lib/puppet/parser/functions/lstrip.rb b/lib/puppet/parser/functions/lstrip.rb index 129d3bd..16e0006 100644 --- a/lib/puppet/parser/functions/lstrip.rb +++ b/lib/puppet/parser/functions/lstrip.rb @@ -1,38 +1,37 @@ # frozen_string_literal: true # # lstrip.rb # module Puppet::Parser::Functions - newfunction(:lstrip, :type => :rvalue, :doc => <<-DOC + newfunction(:lstrip, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Strips leading spaces to the left of a string. @return [String] The stripped string > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`max`](https://puppet.com/docs/puppet/latest/function.html#max) function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "lstrip(): 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, 'lstrip(): 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.lstrip : i } else value.lstrip end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/max.rb b/lib/puppet/parser/functions/max.rb index 8bb5535..173dc0e 100644 --- a/lib/puppet/parser/functions/max.rb +++ b/lib/puppet/parser/functions/max.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # max.rb # module Puppet::Parser::Functions - newfunction(:max, :type => :rvalue, :doc => <<-DOC + newfunction(:max, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the highest value of all arguments. Requires at least one argument. @return The highest value among those passed in > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`lstrip`](https://puppet.com/docs/puppet/latest/function.html#lstrip) function. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, 'max(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.max do |a, b| if a.to_s =~ %r{\A-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end diff --git a/lib/puppet/parser/functions/member.rb b/lib/puppet/parser/functions/member.rb index ecf8419..2795488 100644 --- a/lib/puppet/parser/functions/member.rb +++ b/lib/puppet/parser/functions/member.rb @@ -1,67 +1,66 @@ # frozen_string_literal: true # TODO(Krzysztof Wilczynski): We need to add support for regular expression ... # TODO(Krzysztof Wilczynski): Support for strings and hashes too ... # # member.rb # module Puppet::Parser::Functions - newfunction(:member, :type => :rvalue, :doc => <<-DOC + newfunction(:member, type: :rvalue, doc: <<-DOC @summary This function determines if a variable is a member of an array. The variable can be a string, fixnum, or array. > **Note**: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them. @example **Usage** member(['a','b'], 'b') # Returns: true member(['a', 'b', 'c'], ['a', 'b']) # Returns: true member(['a','b'], 'c') # Returns: false member(['a', 'b', 'c'], ['d', 'b']) # Returns: false > *Note:* Since Puppet 4.0.0 the same can be performed in the Puppet language. For single values the operator `in` can be used: `'a' in ['a', 'b'] # true` For arrays by using operator `-` to compute a diff: `['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted` `['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted` @return Returns whether the given value was a member of the array > **Note** that since Puppet 5.2.0, the general form to test the content of an array or hash is to use the built-in [`any`](https://puppet.com/docs/puppet/latest/function.html#any) and [`all`](https://puppet.com/docs/puppet/latest/function.html#all) functions. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'member(): Requires array to work with') end unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array) raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array') end item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer) [arguments[1]] else arguments[1] end raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty? result = (item - array).empty? return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/merge.rb b/lib/puppet/parser/functions/merge.rb index 0633696..522e484 100644 --- a/lib/puppet/parser/functions/merge.rb +++ b/lib/puppet/parser/functions/merge.rb @@ -1,42 +1,42 @@ # frozen_string_literal: true # # merge.rb # module Puppet::Parser::Functions - newfunction(:merge, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:merge, type: :rvalue, doc: <<-'DOC') do |args| @summary Merges two or more hashes together and returns the resulting hash. @example **Usage** $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." @return [Hash] The merged hash Note that since Puppet 4.0.0 the same merge can be achieved with the + operator. `$merged_hash = $hash1 + $hash2` DOC if args.length < 2 raise Puppet::ParseError, "merge(): wrong number of arguments (#{args.length}; must be at least 2)" end # The hash we accumulate into accumulator = {} # Merge into the accumulator hash args.each do |arg| next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef unless arg.is_a?(Hash) raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments" end accumulator.merge!(arg) end # Return the fully merged hash accumulator end end diff --git a/lib/puppet/parser/functions/min.rb b/lib/puppet/parser/functions/min.rb index cf913d4..1734222 100644 --- a/lib/puppet/parser/functions/min.rb +++ b/lib/puppet/parser/functions/min.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # min.rb # module Puppet::Parser::Functions - newfunction(:min, :type => :rvalue, :doc => <<-DOC + newfunction(:min, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the lowest value of all arguments. Requires at least one argument. @return The lowest value among the given arguments > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`min`](https://puppet.com/docs/puppet/latest/function.html#min) function. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, 'min(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.min do |a, b| if a.to_s =~ %r{\A^-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end diff --git a/lib/puppet/parser/functions/num2bool.rb b/lib/puppet/parser/functions/num2bool.rb index 7bb52db..c74ba01 100644 --- a/lib/puppet/parser/functions/num2bool.rb +++ b/lib/puppet/parser/functions/num2bool.rb @@ -1,50 +1,49 @@ # frozen_string_literal: true # # num2bool.rb # module Puppet::Parser::Functions - newfunction(:num2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:num2bool, type: :rvalue, doc: <<-DOC @summary This function converts a number or a string representation of a number into a true boolean. > *Note:* that since Puppet 5.0.0 the same can be achieved with the Puppet Type System. See the new() function in Puppet for the many available type conversions. @return [Boolean] Boolean(0) # false for any zero or negative number Boolean(1) # true for any positive number DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "num2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 number = arguments[0] case number - when Numeric # rubocop:disable Lint/EmptyWhen : Required for the module to work + when Numeric # Yay, it's a number when String begin number = Float(number) rescue ArgumentError => ex raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}") end else begin number = number.to_s rescue NoMethodError => ex raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}") end end # Truncate Floats number = number.to_i # Return true for any positive number and false otherwise return number > 0 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/parsejson.rb b/lib/puppet/parser/functions/parsejson.rb index f18e060..bb1992e 100644 --- a/lib/puppet/parser/functions/parsejson.rb +++ b/lib/puppet/parser/functions/parsejson.rb @@ -1,31 +1,31 @@ # frozen_string_literal: true # # parsejson.rb # module Puppet::Parser::Functions - newfunction(:parsejson, :type => :rvalue, :doc => <<-DOC + newfunction(:parsejson, type: :rvalue, doc: <<-DOC @summary This function accepts JSON as a string and converts it into the correct Puppet structure. @return convert JSON into Puppet structure > *Note:* The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC - ) do |arguments| + ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 begin PSON.load(arguments[0]) || arguments[1] rescue StandardError => e raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/parseyaml.rb b/lib/puppet/parser/functions/parseyaml.rb index 92d56ff..f80c293 100644 --- a/lib/puppet/parser/functions/parseyaml.rb +++ b/lib/puppet/parser/functions/parseyaml.rb @@ -1,35 +1,35 @@ # frozen_string_literal: true # # parseyaml.rb # module Puppet::Parser::Functions - newfunction(:parseyaml, :type => :rvalue, :doc => <<-DOC + newfunction(:parseyaml, type: :rvalue, doc: <<-DOC @summary This function accepts YAML as a string and converts it into the correct Puppet structure. @return converted YAML into Puppet structure > *Note:* The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC - ) do |arguments| + ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 require 'yaml' begin YAML.load(arguments[0]) || arguments[1] # rubocop:disable Security/YAMLLoad : using YAML.safe_load causes the code to break # in ruby 1.9.3 Psych::SyntaxError is a RuntimeException # this still needs to catch that and work also on rubies that # do not have Psych available. rescue StandardError, Psych::SyntaxError => e # rubocop:disable Lint/ShadowedException : See above raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/pick.rb b/lib/puppet/parser/functions/pick.rb index d85e785..34450c5 100644 --- a/lib/puppet/parser/functions/pick.rb +++ b/lib/puppet/parser/functions/pick.rb @@ -1,34 +1,34 @@ # frozen_string_literal: true # # pick.rb # module Puppet::Parser::Functions - newfunction(:pick, :type => :rvalue, :doc => <<-EOS + newfunction(:pick, type: :rvalue, doc: <<-EOS @summary This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string. @return the first value in a list of values that is not undefined or an empty string. Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: ```$real_jenkins_version = pick($::jenkins_version, '1.449')``` > *Note:* The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. EOS - ) do |args| + ) do |args| args = args.compact args.delete(:undef) args.delete(:undefined) args.delete('') raise Puppet::ParseError, 'pick(): must receive at least one non empty value' if args[0].to_s.empty? return args[0] end end diff --git a/lib/puppet/parser/functions/pick_default.rb b/lib/puppet/parser/functions/pick_default.rb index a36107a..0915df1 100644 --- a/lib/puppet/parser/functions/pick_default.rb +++ b/lib/puppet/parser/functions/pick_default.rb @@ -1,42 +1,42 @@ # frozen_string_literal: true # # pick_default.rb # module Puppet::Parser::Functions - newfunction(:pick_default, :type => :rvalue, :doc => <<-DOC + newfunction(:pick_default, type: :rvalue, doc: <<-DOC @summary This function will return the first value in a list of values that is not undefined or an empty string. @return This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string If no value is found, it will return the last argument. Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: $real_jenkins_version = pick_default($::jenkins_version, '1.449') > *Note:* The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. Contrary to the pick() function, the pick_default does not fail if all arguments are empty. This allows pick_default to use an empty value as default. DOC - ) do |args| + ) do |args| raise 'Must receive at least one argument.' if args.empty? default = args.last args = args[0..-2].compact args.delete(:undef) args.delete(:undefined) args.delete('') args << default return args[0] end end diff --git a/lib/puppet/parser/functions/prefix.rb b/lib/puppet/parser/functions/prefix.rb index ad6faeb..04ed267 100644 --- a/lib/puppet/parser/functions/prefix.rb +++ b/lib/puppet/parser/functions/prefix.rb @@ -1,58 +1,57 @@ # frozen_string_literal: true # # prefix.rb # module Puppet::Parser::Functions - newfunction(:prefix, :type => :rvalue, :doc => <<-DOC + newfunction(:prefix, type: :rvalue, doc: <<-DOC @summary This function applies a prefix to all elements in an array or a hash. @example **Usage** prefix(['a','b','c'], 'p') Will return: ['pa','pb','pc'] > *Note:* since Puppet 4.0.0 the general way to modify values is in array is by using the map function in Puppet. This example does the same as the example above: ['a', 'b', 'c'].map |$x| { "p${x}" } @return [Hash] or [Array] The passed values now contains the passed prefix DOC - ) do |arguments| - + ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end prefix = arguments[1] if arguments[1] if prefix unless prefix.is_a?(String) raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}" end end result = if enumerable.is_a?(Array) # Turn everything into string same as join would do ... enumerable.map do |i| i = i.to_s prefix ? prefix + i : i end else Hash[enumerable.map do |k, v| k = k.to_s [prefix ? prefix + k : k, v] end] end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/private.rb b/lib/puppet/parser/functions/private.rb index 4589c62..037d2b2 100644 --- a/lib/puppet/parser/functions/private.rb +++ b/lib/puppet/parser/functions/private.rb @@ -1,22 +1,22 @@ # frozen_string_literal: true # # private.rb # module Puppet::Parser::Functions - newfunction(:private, :doc => <<-'DOC' + newfunction(:private, doc: <<-'DOC' @summary **Deprecated:** Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. @return Sets the current class or definition as private DOC - ) do |args| + ) do |args| warning("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Layout/LineLength : Cannot shorten this line unless Puppet::Parser::Functions.autoloader.loaded?(:assert_private) Puppet::Parser::Functions.autoloader.load(:assert_private) end function_assert_private([(args[0] unless args.empty?)]) end end diff --git a/lib/puppet/parser/functions/pry.rb b/lib/puppet/parser/functions/pry.rb index 890008a..8fb7d20 100644 --- a/lib/puppet/parser/functions/pry.rb +++ b/lib/puppet/parser/functions/pry.rb @@ -1,37 +1,37 @@ # frozen_string_literal: true # # pry.rb # module Puppet::Parser::Functions - newfunction(:pry, :type => :statement, :doc => <<-DOC + newfunction(:pry, type: :statement, doc: <<-DOC @summary This function invokes a pry debugging session in the current scope object. This is useful for debugging manifest code at specific points during a compilation. @return debugging information @example **Usage** `pry()` DOC - ) do |arguments| + ) do |arguments| begin require 'pry' rescue LoadError raise(Puppet::Error, "pry(): Requires the 'pry' rubygem to use, but it was not found") end # ## Run `catalog` to see the contents currently compiling catalog ## Run `cd catalog` and `ls` to see catalog methods and instance variables ## Run `@resource_table` to see the current catalog resource table # if $stdout.isatty binding.pry # rubocop:disable Lint/Debugger else Puppet.warning 'pry(): cowardly refusing to start the debugger on a daemonized server' end end end diff --git a/lib/puppet/parser/functions/pw_hash.rb b/lib/puppet/parser/functions/pw_hash.rb index 91dd4d3..54deb46 100644 --- a/lib/puppet/parser/functions/pw_hash.rb +++ b/lib/puppet/parser/functions/pw_hash.rb @@ -1,72 +1,72 @@ # frozen_string_literal: true # 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. # Puppet::Parser::Functions.newfunction( :pw_hash, - :type => :rvalue, - :arity => 3, - :doc => <<-DOC + type: :rvalue, + arity: 3, + doc: <<-DOC, @summary Hashes a password using the crypt function. Provides a hash usable on most POSIX systems. The first argument to this function is the password to hash. If it is undef or an empty string, this function returns undef. The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are: |Hash type |Specifier| |---------------------|---------| |MD5 |1 | |SHA-256 |5 | |SHA-512 (recommended)|6 | The third argument to this function is the salt to use. @return [Hash] Provides a hash usable on most POSIX systems. > *Note:*: this uses the Puppet Server's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function. DOC ) do |args| raise ArgumentError, "pw_hash(): wrong number of arguments (#{args.size} for 3)" if args.size != 3 args.map! do |arg| if (defined? Puppet::Pops::Types::PSensitiveType::Sensitive) && (arg.is_a? Puppet::Pops::Types::PSensitiveType::Sensitive) arg.unwrap else arg end end raise ArgumentError, 'pw_hash(): first argument must be a string' unless args[0].is_a?(String) || args[0].nil? raise ArgumentError, 'pw_hash(): second argument must be a string' unless args[1].is_a? String hashes = { 'md5' => '1', 'sha-256' => '5', 'sha-512' => '6' } hash_type = hashes[args[1].downcase] raise ArgumentError, "pw_hash(): #{args[1]} is not a valid hash type" if hash_type.nil? raise ArgumentError, 'pw_hash(): third argument must be a string' unless args[2].is_a? String raise ArgumentError, 'pw_hash(): third argument must not be empty' if args[2].empty? - raise ArgumentError, 'pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]' unless args[2] =~ %r{\A[a-zA-Z0-9./]+\z} + raise ArgumentError, 'pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]' unless %r{\A[a-zA-Z0-9./]+\z}.match?(args[2]) password = args[0] return nil if password.nil? || password.empty? salt = "$#{hash_type}$#{args[2]}" # handle weak implementations of String#crypt if 'test'.crypt('$1$1') != '$1$1$Bp8CU9Oujr9SSEw53WV6G.' # JRuby < 1.7.17 # MS Windows and other systems that don't support enhanced salts raise Puppet::ParseError, 'system does not support enhanced salts' unless RUBY_PLATFORM == 'java' # puppetserver bundles Apache Commons Codec org.apache.commons.codec.digest.Crypt.crypt(password.to_java_bytes, salt) else password.crypt(salt) end end diff --git a/lib/puppet/parser/functions/range.rb b/lib/puppet/parser/functions/range.rb index 6d6c116..5410943 100644 --- a/lib/puppet/parser/functions/range.rb +++ b/lib/puppet/parser/functions/range.rb @@ -1,97 +1,96 @@ # frozen_string_literal: true # # range.rb # # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... module Puppet::Parser::Functions - newfunction(:range, :type => :rvalue, :doc => <<-DOC + newfunction(:range, type: :rvalue, doc: <<-DOC @summary When given range in the form of (start, stop) it will extrapolate a range as an array. @return the range is extrapolated as an array @example **Usage** range("0", "9") Will return: [0,1,2,3,4,5,6,7,8,9] range("00", "09") Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to integers automatically) range("a", "c") Will return: ["a","b","c"] range("host01", "host10") Will return: ["host01", "host02", ..., "host09", "host10"] range("0", "9", "2") Will return: [0,2,4,6,8] NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail. > *Note:* Passing a third argument will cause the generated range to step by that interval, e.g. The Puppet Language support Integer and Float ranges by using the type system. Those are suitable for iterating a given number of times. @see the step() function in Puppet for skipping values. Integer[0, 9].each |$x| { notice($x) } # notices 0, 1, 2, ... 9 DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.empty? if arguments.size > 1 start = arguments[0] stop = arguments[1] step = arguments[2].nil? ? 1 : arguments[2].to_i.abs raise(ArgumentError, 'range(): 3rd arg (step size) must be a non zero integer (e.g. 1 or -1)') if step.zero? type = '..' # Use the simplest type of Range available in Ruby else # arguments.size == 1 value = arguments[0] m = value.match(%r{^(\w+)(\.\.\.?|\-)(\w+)$}) if m start = m[1] stop = m[3] type = m[2] step = 1 - elsif value =~ %r{^.+$} + elsif %r{^.+$}.match?(value) raise(Puppet::ParseError, "range(): Unable to compute range from the value: #{value}") else raise(Puppet::ParseError, "range(): Unknown range format: #{value}") end end # If we were given an integer, ensure we work with one - if start.to_s =~ %r{^\d+$} + if %r{^\d+$}.match?(start.to_s) start = start.to_i stop = stop.to_i else start = start.to_s stop = stop.to_s end range = case type when %r{^(..|-)$} then (start..stop) when '...' then (start...stop) # Exclusive of last element end result = range.step(step).first(1_000_000).to_a return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/regexpescape.rb b/lib/puppet/parser/functions/regexpescape.rb index 45b70e6..c5dcf8c 100644 --- a/lib/puppet/parser/functions/regexpescape.rb +++ b/lib/puppet/parser/functions/regexpescape.rb @@ -1,34 +1,34 @@ # frozen_string_literal: true # # regexpescape.rb # module Puppet::Parser::Functions - newfunction(:regexpescape, :type => :rvalue, :doc => <<-DOC + newfunction(:regexpescape, type: :rvalue, doc: <<-DOC @summary Regexp escape a string or array of strings. Requires either a single string or an array as an input. @return [String] A string of characters with metacharacters converted to their escaped form. DOC - ) do |arguments| # rubocop:disable Layout/ClosingParenthesisIndentation + ) do |arguments| raise(Puppet::ParseError, "regexpescape(): 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, 'regexpescape(): 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) ? Regexp.escape(i) : i } else Regexp.escape(value) end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/reject.rb b/lib/puppet/parser/functions/reject.rb index 49fe8f8..490249c 100644 --- a/lib/puppet/parser/functions/reject.rb +++ b/lib/puppet/parser/functions/reject.rb @@ -1,38 +1,38 @@ # frozen_string_literal: true # # reject.rb # module Puppet::Parser::Functions - newfunction(:reject, :type => :rvalue, :doc => <<-DOC) do |args| + newfunction(:reject, type: :rvalue, doc: <<-DOC) do |args| @summary This function searches through an array and rejects all elements that match the provided regular expression. @return an array containing all the elements which doesn'' match the provided regular expression @example **Usage** reject(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['bbb','ccc'] > *Note:* Since Puppet 4.0.0 the same is in general done with the filter function. Here is the equivalence of the reject() function: ['aaa','bbb','ccc','aaaddd'].filter |$x| { $x !~ /aaa/ } DOC if args.size != 2 raise Puppet::ParseError, "reject(): Wrong number of arguments given #{args.size} for 2" end ary = args[0] pattern = Regexp.new(args[1]) ary.reject { |e| e =~ pattern } end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/reverse.rb b/lib/puppet/parser/functions/reverse.rb index fc53c6e..38250bb 100644 --- a/lib/puppet/parser/functions/reverse.rb +++ b/lib/puppet/parser/functions/reverse.rb @@ -1,32 +1,31 @@ # frozen_string_literal: true # # reverse.rb # module Puppet::Parser::Functions - newfunction(:reverse, :type => :rvalue, :doc => <<-DOC + newfunction(:reverse, type: :rvalue, doc: <<-DOC @summary Reverses the order of a string or array. @return reversed string or array > *Note:* that the same can be done with the reverse_each() function in Puppet. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "reverse(): 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, 'reverse(): Requires either array or string to work with') end result = value.reverse return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/round.rb b/lib/puppet/parser/functions/round.rb index 8406f09..bb1013a 100644 --- a/lib/puppet/parser/functions/round.rb +++ b/lib/puppet/parser/functions/round.rb @@ -1,36 +1,35 @@ # frozen_string_literal: true # # round.rb # module Puppet::Parser::Functions - newfunction(:round, :type => :rvalue, :doc => <<-DOC + newfunction(:round, type: :rvalue, doc: <<-DOC @summary Rounds a number to the nearest integer @return the rounded value as integer @example ```round(2.9)``` returns ```3``` ```round(2.4)``` returns ```2``` > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |args| - + ) do |args| raise Puppet::ParseError, "round(): Wrong number of arguments given #{args.size} for 1" if args.size != 1 raise Puppet::ParseError, "round(): Expected a Numeric, got #{args[0].class}" unless args[0].is_a? Numeric value = args[0] if value >= 0 Integer(value + 0.5) else Integer(value - 0.5) end end end diff --git a/lib/puppet/parser/functions/rstrip.rb b/lib/puppet/parser/functions/rstrip.rb index 59bba1d..d07ef63 100644 --- a/lib/puppet/parser/functions/rstrip.rb +++ b/lib/puppet/parser/functions/rstrip.rb @@ -1,37 +1,36 @@ # frozen_string_literal: true # # rstrip.rb # module Puppet::Parser::Functions - newfunction(:rstrip, :type => :rvalue, :doc => <<-DOC + newfunction(:rstrip, type: :rvalue, doc: <<-DOC @summary Strips leading spaces to the right of the string. @return the string with leading spaces removed > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "rstrip(): 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, 'rstrip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.rstrip : i } else value.rstrip end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/seeded_rand.rb b/lib/puppet/parser/functions/seeded_rand.rb index be89f99..eb495e8 100644 --- a/lib/puppet/parser/functions/seeded_rand.rb +++ b/lib/puppet/parser/functions/seeded_rand.rb @@ -1,34 +1,34 @@ # frozen_string_literal: true # # seeded_rand.rb # Puppet::Parser::Functions.newfunction( :seeded_rand, - :arity => 2, - :type => :rvalue, - :doc => <<-DOC + arity: 2, + type: :rvalue, + doc: <<-DOC, @summary Generates a random whole number greater than or equal to 0 and less than MAX, using the value of SEED for repeatable randomness. @return random number greater than or equal to 0 and less than MAX @example **Usage:** seeded_rand(MAX, SEED). MAX must be a positive integer; SEED is any string. Generates a random whole number greater than or equal to 0 and less than MAX, using the value of SEED for repeatable randomness. If SEED starts with "$fqdn:", this is behaves the same as `fqdn_rand`. DOC ) do |args| require 'digest/md5' raise(ArgumentError, 'seeded_rand(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 raise(ArgumentError, 'seeded_rand(): second argument must be a string') unless args[1].is_a? String max = args[0].to_i seed = Digest::MD5.hexdigest(args[1]).hex Puppet::Util.deterministic_rand_int(seed, max) end diff --git a/lib/puppet/parser/functions/shell_escape.rb b/lib/puppet/parser/functions/shell_escape.rb index c9b7a2f..113feee 100644 --- a/lib/puppet/parser/functions/shell_escape.rb +++ b/lib/puppet/parser/functions/shell_escape.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true require 'shellwords' # # shell_escape.rb # module Puppet::Parser::Functions - newfunction(:shell_escape, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_escape, type: :rvalue, doc: <<-DOC @summary Escapes a string so that it can be safely used in a Bourne shell command line. @return A string of characters with metacharacters converted to their escaped form. >* 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. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 # explicit conversion to string is required for ruby 1.9 string = arguments[0].to_s result = Shellwords.shellescape(string) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shell_join.rb b/lib/puppet/parser/functions/shell_join.rb index d2c6c5f..12d1652 100644 --- a/lib/puppet/parser/functions/shell_join.rb +++ b/lib/puppet/parser/functions/shell_join.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true require 'shellwords' # # shell_join.rb # module Puppet::Parser::Functions - newfunction(:shell_join, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_join, type: :rvalue, doc: <<-DOC @summary Builds a command line string from the given array of strings. Each array item is escaped for Bourne shell. All items are then joined together, with a single space in between. This function behaves the same as ruby's Shellwords.shelljoin() function @return a command line string DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shell_join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] raise Puppet::ParseError, "First argument is not an Array: #{array.inspect}" unless array.is_a?(Array) # explicit conversion to string is required for ruby 1.9 array = array.map { |item| item.to_s } result = Shellwords.shelljoin(array) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shell_split.rb b/lib/puppet/parser/functions/shell_split.rb index 7ac11ea..1fa3c8e 100644 --- a/lib/puppet/parser/functions/shell_split.rb +++ b/lib/puppet/parser/functions/shell_split.rb @@ -1,29 +1,28 @@ # frozen_string_literal: true require 'shellwords' # # shell_split.rb # module Puppet::Parser::Functions - newfunction(:shell_split, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_split, type: :rvalue, doc: <<-DOC @summary Splits a string into an array of tokens in the same way the Bourne shell does. @return array of tokens This function behaves the same as ruby's Shellwords.shellsplit() function DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shell_split(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 string = arguments[0].to_s result = Shellwords.shellsplit(string) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shuffle.rb b/lib/puppet/parser/functions/shuffle.rb index e7d67cb..c79ec2e 100644 --- a/lib/puppet/parser/functions/shuffle.rb +++ b/lib/puppet/parser/functions/shuffle.rb @@ -1,48 +1,47 @@ # frozen_string_literal: true # # shuffle.rb # module Puppet::Parser::Functions - newfunction(:shuffle, :type => :rvalue, :doc => <<-DOC + newfunction(:shuffle, type: :rvalue, doc: <<-DOC @summary Randomizes the order of a string or array elements. @return randomized string or array DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shuffle(): 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, 'shuffle(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to shuffle ... return result if result.size <= 1 # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result elements = result.size # Simple implementation of Fisher–Yates in-place shuffle ... elements.times do |i| j = rand(elements - i) + i result[j], result[i] = result[i], result[j] end result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/size.rb b/lib/puppet/parser/functions/size.rb index 1f551ac..9942bb1 100644 --- a/lib/puppet/parser/functions/size.rb +++ b/lib/puppet/parser/functions/size.rb @@ -1,53 +1,52 @@ # frozen_string_literal: true # # size.rb # module Puppet::Parser::Functions - newfunction(:size, :type => :rvalue, :doc => <<-DOC + newfunction(:size, type: :rvalue, doc: <<-DOC @summary Returns the number of elements in a string, an array or a hash @return the number of elements in a string, an array or a hash > *Note:* that since Puppet 5.4.0, the length() function in Puppet is preferred over this. For versions of Puppet < 5.4.0 use the stdlib length() function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? item = arguments[0] function_deprecation([:size, 'This method is going to be deprecated, please use the stdlib length function.']) if item.is_a?(String) begin # # Check whether your item is a numeric value or not ... # This will take care about positive and/or negative numbers # for both integer and floating-point values ... # # Please note that Puppet has no notion of hexadecimal # nor octal numbers for its DSL at this point in time ... # Float(item) raise(Puppet::ParseError, 'size(): Requires either string, array or hash to work with') rescue ArgumentError result = item.size end elsif item.is_a?(Array) || item.is_a?(Hash) result = item.size else raise(Puppet::ParseError, 'size(): Unknown type given') end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/sort.rb b/lib/puppet/parser/functions/sort.rb index 42f0e89..29c9f60 100644 --- a/lib/puppet/parser/functions/sort.rb +++ b/lib/puppet/parser/functions/sort.rb @@ -1,33 +1,32 @@ # frozen_string_literal: true # # sort.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(:sort, :type => :rvalue, :doc => <<-DOC + newfunction(:sort, type: :rvalue, doc: <<-DOC @summary Sorts strings and arrays lexically. @return sorted string or array Note that from Puppet 6.0.0 the same function in Puppet will be used instead of this. DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "sort(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] if value.is_a?(Array) value.sort elsif value.is_a?(String) value.split('').sort.join('') end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/squeeze.rb b/lib/puppet/parser/functions/squeeze.rb index c4b6dfa..9fdc3a8 100644 --- a/lib/puppet/parser/functions/squeeze.rb +++ b/lib/puppet/parser/functions/squeeze.rb @@ -1,37 +1,36 @@ # frozen_string_literal: true # # squeeze.rb # module Puppet::Parser::Functions - newfunction(:squeeze, :type => :rvalue, :doc => <<-DOC + newfunction(:squeeze, type: :rvalue, doc: <<-DOC @summary Returns a new string where runs of the same character that occur in this set are replaced by a single character. @return a new string where runs of the same character that occur in this set are replaced by a single character. DOC - ) do |arguments| - + ) do |arguments| if (arguments.size != 2) && (arguments.size != 1) raise(Puppet::ParseError, "squeeze(): Wrong number of arguments given #{arguments.size} for 2 or 1") end item = arguments[0] squeezeval = arguments[1] if item.is_a?(Array) if squeezeval item.map { |i| i.squeeze(squeezeval) } else item.map { |i| i.squeeze } end elsif squeezeval item.squeeze(squeezeval) else item.squeeze end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/str2bool.rb b/lib/puppet/parser/functions/str2bool.rb index c3283e2..6723060 100644 --- a/lib/puppet/parser/functions/str2bool.rb +++ b/lib/puppet/parser/functions/str2bool.rb @@ -1,51 +1,50 @@ # frozen_string_literal: true # # str2bool.rb # module Puppet::Parser::Functions - newfunction(:str2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:str2bool, type: :rvalue, doc: <<-DOC @summary This converts a string to a boolean. @return This attempt to convert to boolean strings that contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things like: 0, F,f, N,n, false, FALSE, no to 'false'. > *Note:* that since Puppet 5.0.0 the Boolean data type can convert strings to a Boolean value. See the function new() in Puppet for details what the Boolean data type supports. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? string = arguments[0] # If string is already Boolean, return it if !!string == string # rubocop:disable Style/DoubleNegation : No viable alternative return string end unless string.is_a?(String) raise(Puppet::ParseError, 'str2bool(): Requires string to work with') end # We consider all the yes, no, y, n and so on too ... result = case string # # This is how undef looks like in Puppet ... # We yield false in this case. # when %r{^$}, '' then false # Empty string will be false ... when %r{^(1|t|y|true|yes)$}i then true when %r{^(0|f|n|false|no)$}i then false when %r{^(undef|undefined)$} then false # This is not likely to happen ... else raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/str2saltedpbkdf2.rb b/lib/puppet/parser/functions/str2saltedpbkdf2.rb index 8177a63..f3cd811 100644 --- a/lib/puppet/parser/functions/str2saltedpbkdf2.rb +++ b/lib/puppet/parser/functions/str2saltedpbkdf2.rb @@ -1,70 +1,70 @@ # frozen_string_literal: true # str2saltedpbkdf2.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(:str2saltedpbkdf2, :type => :rvalue, :doc => <<-DOC + newfunction(:str2saltedpbkdf2, type: :rvalue, doc: <<-DOC @summary Convert a string into a salted SHA512 PBKDF2 password hash like requred for OS X / macOS 10.8+ Convert a string into a salted SHA512 PBKDF2 password hash like requred for OS X / macOS 10.8+. Note, however, that Apple changes what's required periodically and this may not work for the latest version of macOS. If that is the case you should get a helpful error message when Puppet tries to set the pasword using the parameters you provide to the user resource. @example Plain text password and salt $pw_info = str2saltedpbkdf2('Pa55w0rd', 'Using s0m3 s@lt', 50000) user { 'jdoe': ensure => present, iterations => $pw_info['interations'], password => $pw_info['password_hex'], salt => $pw_info['salt_hex'], } @example Sensitive password and salt $pw = Sensitive.new('Pa55w0rd') $salt = Sensitive.new('Using s0m3 s@lt') $pw_info = Sensitive.new(str2saltedpbkdf2($pw, $salt, 50000)) user { 'jdoe': ensure => present, iterations => unwrap($pw_info)['interations'], password => unwrap($pw_info)['password_hex'], salt => unwrap($pw_info)['salt_hex'], } @return [Hash] Provides a hash containing the hex version of the password, the hex version of the salt, and iterations. DOC - ) do |args| + ) do |args| require 'openssl' raise ArgumentError, "str2saltedpbkdf2(): wrong number of arguments (#{args.size} for 3)" if args.size != 3 args.map! do |arg| if (defined? Puppet::Pops::Types::PSensitiveType::Sensitive) && (arg.is_a? Puppet::Pops::Types::PSensitiveType::Sensitive) arg.unwrap else arg end end raise ArgumentError, 'str2saltedpbkdf2(): first argument must be a string' unless args[0].is_a?(String) raise ArgumentError, 'str2saltedpbkdf2(): second argument must be a string' unless args[1].is_a?(String) raise ArgumentError, 'str2saltedpbkdf2(): second argument must be at least 8 bytes long' unless args[1].bytesize >= 8 raise ArgumentError, 'str2saltedpbkdf2(): third argument must be an integer' unless args[2].is_a?(Integer) raise ArgumentError, 'str2saltedpbkdf2(): third argument must be between 40,000 and 70,000' unless args[2] > 40_000 && args[2] < 70_000 password = args[0] salt = args[1] iterations = args[2] keylen = 128 digest = OpenSSL::Digest::SHA512.new hash = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, keylen, digest) { 'password_hex' => hash.unpack('H*').first, 'salt_hex' => salt.unpack('H*').first, 'iterations' => iterations, } end end diff --git a/lib/puppet/parser/functions/str2saltedsha512.rb b/lib/puppet/parser/functions/str2saltedsha512.rb index eade8c0..a1a278b 100644 --- a/lib/puppet/parser/functions/str2saltedsha512.rb +++ b/lib/puppet/parser/functions/str2saltedsha512.rb @@ -1,38 +1,38 @@ # frozen_string_literal: true # # str2saltedsha512.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(:str2saltedsha512, :type => :rvalue, :doc => <<-DOC + newfunction(:str2saltedsha512, type: :rvalue, doc: <<-DOC @summary This converts a string to a salted-SHA512 password hash (which is used for OS X versions >= 10.7). @return converted string as a hex version of a salted-SHA512 password hash Given any simple string, you will get a hex version of a salted-SHA512 password hash that can be inserted into your Puppet manifests as a valid password attribute. DOC - ) do |arguments| + ) do |arguments| require 'digest/sha2' raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments passed (#{arguments.size} but we require 1)") if arguments.size != 1 password = arguments[0] unless password.is_a?(String) raise(Puppet::ParseError, "str2saltedsha512(): Requires a String argument, you passed: #{password.class}") end seedint = rand(2**31 - 1) seedstring = Array(seedint).pack('L') saltedpass = Digest::SHA512.digest(seedstring + password) (seedstring + saltedpass).unpack('H*')[0] end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/strip.rb b/lib/puppet/parser/functions/strip.rb index 9af124a..6f11736 100644 --- a/lib/puppet/parser/functions/strip.rb +++ b/lib/puppet/parser/functions/strip.rb @@ -1,43 +1,42 @@ # frozen_string_literal: true # # strip.rb # module Puppet::Parser::Functions - newfunction(:strip, :type => :rvalue, :doc => <<-DOC + newfunction(:strip, type: :rvalue, doc: <<-DOC @summary This function removes leading and trailing whitespace from a string or from every string inside an array. @return String or Array converted @example **Usage** strip(" aaa ") Would result in: "aaa" > *Note:*: from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "strip(): 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, 'strip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.strip : i } else value.strip end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/suffix.rb b/lib/puppet/parser/functions/suffix.rb index e5d5f18..5c519ba 100644 --- a/lib/puppet/parser/functions/suffix.rb +++ b/lib/puppet/parser/functions/suffix.rb @@ -1,62 +1,61 @@ # frozen_string_literal: true # # suffix.rb # module Puppet::Parser::Functions - newfunction(:suffix, :type => :rvalue, :doc => <<-DOC + newfunction(:suffix, type: :rvalue, doc: <<-DOC @summary This function applies a suffix to all elements in an array, or to the keys in a hash. @return Array or Hash with updated elements containing the passed suffix @example **Usage** suffix(['a','b','c'], 'p') Will return: ['ap','bp','cp'] > *Note:* that since Puppet 4.0.0 the general way to modify values is in array is by using the map function in Puppet. This example does the same as the example above: ```['a', 'b', 'c'].map |$x| { "${x}p" }``` DOC - ) do |arguments| - + ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "suffix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "suffix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a? String raise Puppet::ParseError, "suffix(): expected second argument to be a String, got #{suffix.inspect}" end end result = if enumerable.is_a?(Array) # Turn everything into string same as join would do ... enumerable.map do |i| i = i.to_s suffix ? i + suffix : i end else Hash[enumerable.map do |k, v| k = k.to_s [suffix ? k + suffix : k, v] end] end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/swapcase.rb b/lib/puppet/parser/functions/swapcase.rb index dd290ed..cddd289 100644 --- a/lib/puppet/parser/functions/swapcase.rb +++ b/lib/puppet/parser/functions/swapcase.rb @@ -1,41 +1,40 @@ # frozen_string_literal: true # # swapcase.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(:swapcase, :type => :rvalue, :doc => <<-DOC + newfunction(:swapcase, type: :rvalue, doc: <<-DOC @summary This function will swap the existing case of a string. @return string with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase @example **Usage** swapcase("aBcD") Would result in: "AbCd" DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "swapcase(): 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, 'swapcase(): 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.swapcase : i } else value.swapcase end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/time.rb b/lib/puppet/parser/functions/time.rb index b6a75b0..e154643 100644 --- a/lib/puppet/parser/functions/time.rb +++ b/lib/puppet/parser/functions/time.rb @@ -1,60 +1,59 @@ # frozen_string_literal: true # # time.rb # module Puppet::Parser::Functions - newfunction(:time, :type => :rvalue, :doc => <<-DOC + newfunction(:time, type: :rvalue, doc: <<-DOC @summary This function will return the current time since epoch as an integer. @return the current time since epoch as an integer. @example **Usage** time() Will return something like: 1311972653 > *Note:* that since Puppet 4.8.0 the Puppet language has the data types Timestamp (a point in time) and Timespan (a duration). The following example is equivalent to calling time() without any arguments: ```Timestamp()``` DOC - ) do |arguments| - + ) do |arguments| # The Time Zone argument is optional ... time_zone = arguments[0] if arguments[0] if !arguments.empty? && (arguments.size != 1) raise(Puppet::ParseError, "time(): Wrong number of arguments given #{arguments.size} for 0 or 1") end time = Time.new # There is probably a better way to handle Time Zone ... if time_zone && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone result = local_time.localtime.strftime('%s') ENV['TZ'] = original_zone else result = time.localtime.strftime('%s') end # Calling Time#to_i on a receiver changes it. Trust me I am the Doctor. result = result.to_i return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/to_bytes.rb b/lib/puppet/parser/functions/to_bytes.rb index 6dee0ff..b1beb5f 100644 --- a/lib/puppet/parser/functions/to_bytes.rb +++ b/lib/puppet/parser/functions/to_bytes.rb @@ -1,40 +1,39 @@ # frozen_string_literal: true # # to_bytes.rb # module Puppet::Parser::Functions - newfunction(:to_bytes, :type => :rvalue, :doc => <<-DOC + newfunction(:to_bytes, type: :rvalue, doc: <<-DOC @summary Converts the argument into bytes, for example 4 kB becomes 4096. @return converted value into bytes Takes a single string value as an argument. These conversions reflect a layperson's understanding of 1 MB = 1024 KB, when in fact 1 MB = 1000 KB, and 1 MiB = 1024 KiB. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] return arg if arg.is_a? Numeric value, prefix = *%r{([0-9.e+-]*)\s*([^bB]?)}.match(arg)[1, 2] value = value.to_f case prefix when '' then return value.to_i when 'k' then return (value * (1 << 10)).to_i when 'M' then return (value * (1 << 20)).to_i when 'G' then return (value * (1 << 30)).to_i when 'T' then return (value * (1 << 40)).to_i when 'P' then return (value * (1 << 50)).to_i when 'E' then return (value * (1 << 60)).to_i else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" end end end diff --git a/lib/puppet/parser/functions/try_get_value.rb b/lib/puppet/parser/functions/try_get_value.rb index 255666e..8df9530 100644 --- a/lib/puppet/parser/functions/try_get_value.rb +++ b/lib/puppet/parser/functions/try_get_value.rb @@ -1,62 +1,62 @@ # frozen_string_literal: true # # try_get_value.rb # module Puppet::Parser::Functions newfunction( :try_get_value, - :type => :rvalue, - :arity => -2, - :doc => <<-DOC + type: :rvalue, + arity: -2, + doc: <<-DOC, @summary **DEPRECATED:** this function is deprecated, please use dig() instead. @return Looks up into a complex structure of arrays and hashes and returns a value or the default value if nothing was found. Key can contain slashes to describe path components. The function will go down the structure and try to extract the required value. `` $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = try_get_value($data, 'a/b/2', 'not_found', '/') => $value = 'b3' ``` ``` a -> first hash key b -> second hash key 2 -> array index starting with 0 not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. / -> (optional) path delimiter. Defaults to '/'. ``` In addition to the required "key" argument, "try_get_value" accepts default argument. It will be returned if no value was found or a path component is missing. And the fourth argument can set a variable path separator. DOC ) do |args| warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.') data = args[0] path = args[1] || '' default = args[2] if !(data.is_a?(Hash) || data.is_a?(Array)) || path == '' return default || data end separator = args[3] || '/' path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key } function_dig([data, path, default]) end end diff --git a/lib/puppet/parser/functions/type.rb b/lib/puppet/parser/functions/type.rb index 194a907..57dd3e1 100644 --- a/lib/puppet/parser/functions/type.rb +++ b/lib/puppet/parser/functions/type.rb @@ -1,31 +1,30 @@ # frozen_string_literal: true # # type.rb # module Puppet::Parser::Functions - newfunction(:type, :type => :rvalue, :doc => <<-DOC + newfunction(:type, type: :rvalue, doc: <<-DOC @summary **DEPRECATED:** This function will cease to function on Puppet 4; please use type3x() before upgrading to Puppet 4 for backwards-compatibility, or migrate to the new parser's typing system. @return the type when passed a value. Type can be one of: * string * array * hash * float * integer * boolean DOC - ) do |args| - + ) do |args| warning("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Layout/LineLength : Cannot reduce line length unless Puppet::Parser::Functions.autoloader.loaded?(:type3x) Puppet::Parser::Functions.autoloader.load(:type3x) end function_type3x(args) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/type3x.rb b/lib/puppet/parser/functions/type3x.rb index c78f496..49903b9 100644 --- a/lib/puppet/parser/functions/type3x.rb +++ b/lib/puppet/parser/functions/type3x.rb @@ -1,52 +1,52 @@ # frozen_string_literal: true # # type3x.rb # module Puppet::Parser::Functions - newfunction(:type3x, :type => :rvalue, :doc => <<-DOC + newfunction(:type3x, type: :rvalue, doc: <<-DOC @summary **DEPRECATED:** This function will be removed when Puppet 3 support is dropped; please migrate to the new parser's typing system. @return the type when passed a value. Type can be one of: * string * array * hash * float * integer * boolean DOC - ) do |args| + ) do |args| raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") unless args.size == 1 value = args[0] klass = value.class unless [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) # rubocop:disable Lint/UnifiedInteger raise(Puppet::ParseError, 'type3x(): Unknown type') end klass = klass.to_s # Ugly ... # We note that Integer is the parent to Bignum and Fixnum ... result = case klass when %r{^(?:Big|Fix)num$} then 'integer' when %r{^(?:True|False)Class$} then 'boolean' else klass end if result == 'String' if value == value.to_i.to_s result = 'Integer' elsif value == value.to_f.to_s result = 'Float' end end return result.downcase end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/union.rb b/lib/puppet/parser/functions/union.rb index 9bda29d..353e51e 100644 --- a/lib/puppet/parser/functions/union.rb +++ b/lib/puppet/parser/functions/union.rb @@ -1,31 +1,30 @@ # frozen_string_literal: true # # union.rb # module Puppet::Parser::Functions - newfunction(:union, :type => :rvalue, :doc => <<-DOC + newfunction(:union, type: :rvalue, doc: <<-DOC @summary This function returns a union of two or more arrays. @return a unionized array of two or more arrays @example **Usage** union(["a","b","c"],["b","c","d"]) Would return: ["a","b","c","d"] DOC - ) do |arguments| - + ) do |arguments| # Check that 2 or more arguments have been given ... raise(Puppet::ParseError, "union(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 arguments.each do |argument| raise(Puppet::ParseError, 'union(): Every parameter must be an array') unless argument.is_a?(Array) end arguments.reduce(:|) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/unique.rb b/lib/puppet/parser/functions/unique.rb index 3c29f58..7efdaa3 100644 --- a/lib/puppet/parser/functions/unique.rb +++ b/lib/puppet/parser/functions/unique.rb @@ -1,52 +1,51 @@ # frozen_string_literal: true # # unique.rb # module Puppet::Parser::Functions - newfunction(:unique, :type => :rvalue, :doc => <<-DOC + newfunction(:unique, type: :rvalue, doc: <<-DOC @summary This function will remove duplicates from strings and arrays. @return String or array with duplicates removed @example **Usage** unique("aabbcc") Will return: abc You can also use this with arrays: unique(["a","a","b","b","c","c"]) This returns: ["a","b","c"] DOC - ) do |arguments| - + ) do |arguments| if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 function_deprecation([:unique, 'This method is deprecated, please use the core puppet unique function. There is further documentation for the function in the release notes of Puppet 5.0.']) end raise(Puppet::ParseError, "unique(): 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, 'unique(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result result = result.uniq # Remove duplicates ... result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/unix2dos.rb b/lib/puppet/parser/functions/unix2dos.rb index 351af73..95d9dfc 100644 --- a/lib/puppet/parser/functions/unix2dos.rb +++ b/lib/puppet/parser/functions/unix2dos.rb @@ -1,22 +1,21 @@ # frozen_string_literal: true # Custom Puppet function to convert unix to dos format module Puppet::Parser::Functions - newfunction(:unix2dos, :type => :rvalue, :arity => 1, :doc => <<-DOC + newfunction(:unix2dos, type: :rvalue, arity: 1, doc: <<-DOC @summary Returns the DOS version of the given string. @return the DOS version of the given string. Takes a single string argument. DOC - ) do |arguments| - + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'unix2dos(): Requires string as argument') end arguments[0].gsub(%r{\r*\n}, "\r\n") end end diff --git a/lib/puppet/parser/functions/upcase.rb b/lib/puppet/parser/functions/upcase.rb index 5791769..a7685d1 100644 --- a/lib/puppet/parser/functions/upcase.rb +++ b/lib/puppet/parser/functions/upcase.rb @@ -1,49 +1,48 @@ # frozen_string_literal: true # # upcase.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(:upcase, :type => :rvalue, :doc => <<-DOC + newfunction(:upcase, type: :rvalue, doc: <<-DOC @summary Converts a string or an array of strings to uppercase. @return converted string ot array of strings to uppercase @example **Usage** upcase("abcd") Will return ABCD > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "upcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.respond_to?(:upcase) raise(Puppet::ParseError, 'upcase(): Requires an array, hash or object that responds to upcase in order to work') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.map { |i| function_upcase([i]) } elsif value.is_a?(Hash) result = {} value.each_pair do |k, v| result[function_upcase([k])] = function_upcase([v]) end else result = value.upcase end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/uriescape.rb b/lib/puppet/parser/functions/uriescape.rb index b85d1f0..b7de4c1 100644 --- a/lib/puppet/parser/functions/uriescape.rb +++ b/lib/puppet/parser/functions/uriescape.rb @@ -1,39 +1,38 @@ # frozen_string_literal: true require 'uri' # # uriescape.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(:uriescape, :type => :rvalue, :doc => <<-DOC + newfunction(:uriescape, type: :rvalue, doc: <<-DOC @summary Urlencodes a string or array of strings. Requires either a single string or an array as an input. @return [String] a string that contains the converted value DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "uriescape(): 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, 'uriescape(): 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) ? URI.escape(i) : i } else URI.escape(value) end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/validate_absolute_path.rb b/lib/puppet/parser/functions/validate_absolute_path.rb index 9fe9914..e0ea72b 100644 --- a/lib/puppet/parser/functions/validate_absolute_path.rb +++ b/lib/puppet/parser/functions/validate_absolute_path.rb @@ -1,61 +1,61 @@ # frozen_string_literal: true # # validate_absolute_path.rb # module Puppet::Parser::Functions - newfunction(:validate_absolute_path, :doc => <<-DOC) do |args| + newfunction(:validate_absolute_path, doc: <<-DOC) do |args| @summary Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @return passes when the string is an absolute path or raise an error when it is not and fails compilation @example **Usage** The following values will pass: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' validate_absolute_path($my_path) $my_path2 = '/var/lib/puppet' validate_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet'] validate_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet','/usr/share/puppet'] validate_absolute_path($my_path4) The following values will fail, causing compilation to abort: validate_absolute_path(true) validate_absolute_path('../var/lib/puppet') validate_absolute_path('var/lib/puppet') validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = undef validate_absolute_path($undefined) DOC require 'puppet/util' if args.empty? raise Puppet::ParseError, "validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # put arg to candidate var to be able to replace it candidates = arg # if arg is just a string with a path to test, convert it to an array # to avoid test code duplication unless arg.is_a?(Array) candidates = Array.new(1, arg) end # iterate over all paths within the candidates array candidates.each do |path| unless function_is_absolute_path([path]) raise Puppet::ParseError, "#{path.inspect} is not an absolute path." end end end end end diff --git a/lib/puppet/parser/functions/validate_array.rb b/lib/puppet/parser/functions/validate_array.rb index 83840d4..15cbc44 100644 --- a/lib/puppet/parser/functions/validate_array.rb +++ b/lib/puppet/parser/functions/validate_array.rb @@ -1,42 +1,42 @@ # frozen_string_literal: true # # validate_array.rb # module Puppet::Parser::Functions - newfunction(:validate_array, :doc => <<-DOC) do |args| + newfunction(:validate_array, doc: <<-DOC) do |args| @summary Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. @return validate array @example **Usage** The following values will pass: $my_array = [ 'one', 'two' ] validate_array($my_array) The following values will fail, causing compilation to abort: validate_array(true) validate_array('some_string') $undefined = undef validate_array($undefined) DOC function_deprecation([:validate_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_array(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Array) raise Puppet::ParseError, "#{arg.inspect} is not an Array. It looks to be a #{arg.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_augeas.rb b/lib/puppet/parser/functions/validate_augeas.rb index e79b6f7..55f932f 100644 --- a/lib/puppet/parser/functions/validate_augeas.rb +++ b/lib/puppet/parser/functions/validate_augeas.rb @@ -1,96 +1,96 @@ # frozen_string_literal: true require 'tempfile' # # validate_augaes.rb # module Puppet::Parser::Functions - newfunction(:validate_augeas, :doc => <<-DOC + newfunction(:validate_augeas, doc: <<-DOC @summary Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. @return validate string using an Augeas lens @example **Usage** If you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) If you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') DOC - ) do |args| + ) do |args| unless Puppet.features.augeas? raise Puppet::ParseError, 'validate_augeas(): this function requires the augeas feature. See http://docs.puppetlabs.com/guides/augeas.html#pre-requisites for how to activate it.' end if (args.length < 2) || (args.length > 4) raise Puppet::ParseError, "validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)" end msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" require 'augeas' aug = Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) begin content = args[0] # Test content in a temporary file tmpfile = Tempfile.new('validate_augeas') begin tmpfile.write(content) ensure tmpfile.close end # Check for syntax lens = args[1] aug.transform( - :lens => lens, - :name => 'Validate_augeas', - :incl => tmpfile.path, + lens: lens, + name: 'Validate_augeas', + incl: tmpfile.path, ) aug.load! unless aug.match("/augeas/files#{tmpfile.path}//error").empty? error = aug.get("/augeas/files#{tmpfile.path}//error/message") msg += " with error: #{error}" raise Puppet::ParseError, msg end # Launch unit tests tests = args[2] || [] aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" raise Puppet::ParseError, msg unless aug.match(t).empty? end ensure aug.close tmpfile.unlink end end end diff --git a/lib/puppet/parser/functions/validate_bool.rb b/lib/puppet/parser/functions/validate_bool.rb index 9cf9436..125d262 100644 --- a/lib/puppet/parser/functions/validate_bool.rb +++ b/lib/puppet/parser/functions/validate_bool.rb @@ -1,41 +1,41 @@ # frozen_string_literal: true # # validate_bool.rb # module Puppet::Parser::Functions - newfunction(:validate_bool, :doc => <<-DOC + newfunction(:validate_bool, doc: <<-DOC @summary Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. @return validate boolean @example **Usage** The following values will pass: $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) The following values will fail, causing compilation to abort: $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) DOC - ) do |args| + ) do |args| if args.empty? raise Puppet::ParseError, "validate_bool(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless function_is_bool([arg]) raise Puppet::ParseError, "#{arg.inspect} is not a boolean. It looks to be a #{arg.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_cmd.rb b/lib/puppet/parser/functions/validate_cmd.rb index 1142fb8..16b4ab9 100644 --- a/lib/puppet/parser/functions/validate_cmd.rb +++ b/lib/puppet/parser/functions/validate_cmd.rb @@ -1,73 +1,73 @@ # frozen_string_literal: true require 'puppet/util/execution' require 'tempfile' # # validate_cmd.rb # module Puppet::Parser::Functions - newfunction(:validate_cmd, :doc => <<-DOC + newfunction(:validate_cmd, doc: <<-DOC @summary Perform validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a % as a placeholder for the file path (will default to the end). If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. @return validate of a string with an external command A helpful error message can be returned like this: @example **Usage** Defaults to end of path validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') % as file location validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') DOC - ) do |args| + ) do |args| if (args.length < 2) || (args.length > 3) raise Puppet::ParseError, "validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)" end msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}" content = args[0] checkscript = args[1] # Test content in a temporary file tmpfile = Tempfile.new('validate_cmd') begin tmpfile.write(content) tmpfile.close - check_with_correct_location = if checkscript =~ %r{\s%(\s|$)} + check_with_correct_location = if %r{\s%(\s|$)}.match?(checkscript) checkscript.gsub(%r{%}, tmpfile.path) else "#{checkscript} #{tmpfile.path}" end if Puppet::Util::Execution.respond_to?('execute') Puppet::Util::Execution.execute(check_with_correct_location) else Puppet::Util.execute(check_with_correct_location) end rescue Puppet::ExecutionFailure => detail msg += "\n#{detail}" raise Puppet::ParseError, msg rescue StandardError => detail msg += "\n#{detail.class.name} #{detail}" raise Puppet::ParseError, msg ensure tmpfile.unlink end end end diff --git a/lib/puppet/parser/functions/validate_domain_name.rb b/lib/puppet/parser/functions/validate_domain_name.rb index 3cb389b..0ed576f 100644 --- a/lib/puppet/parser/functions/validate_domain_name.rb +++ b/lib/puppet/parser/functions/validate_domain_name.rb @@ -1,49 +1,48 @@ # frozen_string_literal: true # # validate_domain_name.rb # module Puppet::Parser::Functions - newfunction(:validate_domain_name, :doc => <<-DOC + newfunction(:validate_domain_name, doc: <<-DOC @summary Validate that all values passed are syntactically correct domain names. Fail compilation if any value fails this check. @return passes when the given values are syntactically correct domain names or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_domain_name = 'server.domain.tld' validate_domain_name($my_domain_name) validate_domain_name('domain.tld', 'puppet.com', $my_domain_name) The following values will fail, causing compilation to abort: validate_domain_name(1) validate_domain_name(true) validate_domain_name('invalid domain') validate_domain_name('-foo.example.com') validate_domain_name('www.example.2com') DOC - ) do |args| - + ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_domain_name(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" unless function_is_domain_name([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" end end end end diff --git a/lib/puppet/parser/functions/validate_email_address.rb b/lib/puppet/parser/functions/validate_email_address.rb index 2568a96..ae847b5 100644 --- a/lib/puppet/parser/functions/validate_email_address.rb +++ b/lib/puppet/parser/functions/validate_email_address.rb @@ -1,45 +1,45 @@ # frozen_string_literal: true # # validate_email_address.rb # module Puppet::Parser::Functions - newfunction(:validate_email_address, :doc => <<-DOC + newfunction(:validate_email_address, doc: <<-DOC @summary Validate that all values passed are valid email addresses. Fail compilation if any value fails this check. @return Fail compilation if any value fails this check. @example **Usage** The following values will pass: $my_email = "waldo@gmail.com" validate_email_address($my_email) validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email) The following values will fail, causing compilation to abort: $some_array = [ 'bad_email@/d/efdf.com' ] validate_email_address($some_array) DOC - ) do |args| + ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_email_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" unless function_is_email_address([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" end end end end diff --git a/lib/puppet/parser/functions/validate_hash.rb b/lib/puppet/parser/functions/validate_hash.rb index ef8d269..c34f1e4 100644 --- a/lib/puppet/parser/functions/validate_hash.rb +++ b/lib/puppet/parser/functions/validate_hash.rb @@ -1,44 +1,43 @@ # frozen_string_literal: true # # validate_hash.rb # module Puppet::Parser::Functions - newfunction(:validate_hash, :doc => <<-DOC + newfunction(:validate_hash, doc: <<-DOC @summary Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. @return validate hash @example **Usage** The following values will pass: $my_hash = { 'one' => 'two' } validate_hash($my_hash) The following values will fail, causing compilation to abort: validate_hash(true) validate_hash('some_string') $undefined = undef validate_hash($undefined) DOC - ) do |args| - + ) do |args| function_deprecation([:validate_hash, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_hash(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Hash) raise Puppet::ParseError, "#{arg.inspect} is not a Hash. It looks to be a #{arg.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_integer.rb b/lib/puppet/parser/functions/validate_integer.rb index b734ede..4ec05b0 100644 --- a/lib/puppet/parser/functions/validate_integer.rb +++ b/lib/puppet/parser/functions/validate_integer.rb @@ -1,143 +1,143 @@ # frozen_string_literal: true # # validate_interger.rb # module Puppet::Parser::Functions - newfunction(:validate_integer, :doc => <<-DOC + newfunction(:validate_integer, doc: <<-DOC @summary Validate that the first argument is an integer (or an array of integers). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not an integer or array of integers, and if arg 2 and arg 3 are not convertable to an integer. @return Validate that the first argument is an integer (or an array of integers). Fail compilation if any of the checks fail. @example **Usage** The following values will pass: validate_integer(1) validate_integer(1, 2) validate_integer(1, 1) validate_integer(1, 2, 0) validate_integer(2, 2, 2) validate_integer(2, '', 0) validate_integer(2, undef, 0) $foo = undef validate_integer(2, $foo, 0) validate_integer([1,2,3,4,5], 6) validate_integer([1,2,3,4,5], 6, 0) Plus all of the above, but any combination of values passed as strings ('1' or "1"). Plus all of the above, but with (correct) combinations of negative integer values. The following values will not: validate_integer(true) validate_integer(false) validate_integer(7.0) validate_integer({ 1 => 2 }) $foo = undef validate_integer($foo) validate_integer($foobaridontexist) validate_integer(1, 0) validate_integer(1, true) validate_integer(1, '') validate_integer(1, undef) validate_integer(1, , 0) validate_integer(1, 2, 3) validate_integer(1, 3, 2) validate_integer(1, 3, true) Plus all of the above, but any combination of values passed as strings ('false' or "false"). Plus all of the above, but with incorrect combinations of negative integer values. Plus all of the above, but with non-integer items in arrays or maximum / minimum argument. DOC - ) do |args| + ) do |args| function_deprecation([:validate_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters raise Puppet::ParseError, "validate_integer(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args # check maximum parameter if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set if args.length > 2 && max == '' max = nil else begin max = Integer(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected second argument to be unset or an Integer, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Integer(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected third argument to be unset or an Integer, got #{min}:#{min.class}" end else min = nil end # ensure that min < max if min && max && min > max raise Puppet::ParseError, "validate_integer(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function validator = ->(num) do # check input < max if max && num > max raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) if min && num < min raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Integer(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected element at array position #{pos} to be an Integer, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Integer(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_ip_address.rb b/lib/puppet/parser/functions/validate_ip_address.rb index 2b1ddb1..32400e2 100644 --- a/lib/puppet/parser/functions/validate_ip_address.rb +++ b/lib/puppet/parser/functions/validate_ip_address.rb @@ -1,63 +1,62 @@ # frozen_string_literal: true # # validate_ip_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ip_address, :doc => <<-DOC + newfunction(:validate_ip_address, doc: <<-DOC @summary Validate that all values passed are valid IP addresses, regardless they are IPv4 or IPv6 Fail compilation if any value fails this check. @return passes when the given values are valid IP addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "1.2.3.4" validate_ip_address($my_ip) validate_ip_address("8.8.8.8", "172.16.0.1", $my_ip) $my_ip = "3ffe:505:2" validate_ip_address(1) validate_ip_address($my_ip) validate_ip_address("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ip_address($some_array) DOC - ) do |args| - + ) do |args| require 'ipaddr' rescuable_exceptions = [ArgumentError] function_deprecation([:validate_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv4? || IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end end end end diff --git a/lib/puppet/parser/functions/validate_ipv4_address.rb b/lib/puppet/parser/functions/validate_ipv4_address.rb index 1e17d9b..9e86690 100644 --- a/lib/puppet/parser/functions/validate_ipv4_address.rb +++ b/lib/puppet/parser/functions/validate_ipv4_address.rb @@ -1,57 +1,56 @@ # frozen_string_literal: true # # validate_ipv4_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ipv4_address, :doc => <<-DOC + newfunction(:validate_ipv4_address, doc: <<-DOC @summary Validate that all values passed are valid IPv4 addresses. Fail compilation if any value fails this check. @return passes when the given values are valid IPv4 addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "1.2.3.4" validate_ipv4_address($my_ip) validate_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ipv4_address($some_array) DOC - ) do |args| - + ) do |args| function_deprecation([:validate_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv4? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end end end end diff --git a/lib/puppet/parser/functions/validate_ipv6_address.rb b/lib/puppet/parser/functions/validate_ipv6_address.rb index e62dcd5..3596e69 100644 --- a/lib/puppet/parser/functions/validate_ipv6_address.rb +++ b/lib/puppet/parser/functions/validate_ipv6_address.rb @@ -1,59 +1,58 @@ # frozen_string_literal: true # # validate_ipv7_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ipv6_address, :doc => <<-DOC + newfunction(:validate_ipv6_address, doc: <<-DOC @summary Validate that all values passed are valid IPv6 addresses. Fail compilation if any value fails this check. @return passes when the given values are valid IPv6 addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "3ffe:505:2" validate_ipv6_address(1) validate_ipv6_address($my_ip) validate_bool("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ true, false, "garbage string", "1.2.3.4" ] validate_ipv6_address($some_array) DOC - ) do |args| - + ) do |args| function_deprecation([:validate_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end end end end diff --git a/lib/puppet/parser/functions/validate_numeric.rb b/lib/puppet/parser/functions/validate_numeric.rb index 5db62f0..1bbc667 100644 --- a/lib/puppet/parser/functions/validate_numeric.rb +++ b/lib/puppet/parser/functions/validate_numeric.rb @@ -1,103 +1,103 @@ # frozen_string_literal: true # # validate_numeric.rb # module Puppet::Parser::Functions - newfunction(:validate_numeric, :doc => <<-DOC + newfunction(:validate_numeric, doc: <<-DOC @summary Validate that the first argument is a numeric value (or an array of numeric values). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not a numeric (Integer or Float) or array of numerics, and if arg 2 and arg 3 are not convertable to a numeric. @return Validate that the first argument is a numeric value (or an array of numeric values). Fail compilation if any of the checks fail. For passing and failing usage, see `validate_integer()`. It is all the same for validate_numeric, yet now floating point values are allowed, too. DOC - ) do |args| + ) do |args| function_deprecation([:validate_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters raise Puppet::ParseError, "validate_numeric(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args # check maximum parameter if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set if args.length > 2 && max == '' max = nil else begin max = Float(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected second argument to be unset or a Numeric, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Float(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected third argument to be unset or a Numeric, got #{min}:#{min.class}" end else min = nil end # ensure that min < max if min && max && min > max raise Puppet::ParseError, "validate_numeric(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function validator = ->(num) do # check input < max if max && num > max raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) if min && num < min raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Float(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected element at array position #{pos} to be a Numeric, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be a Numeric or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Float(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected first argument to be a Numeric or Array, got #{input.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_re.rb b/lib/puppet/parser/functions/validate_re.rb index fb15c34..f116280 100644 --- a/lib/puppet/parser/functions/validate_re.rb +++ b/lib/puppet/parser/functions/validate_re.rb @@ -1,60 +1,60 @@ # frozen_string_literal: true # # validate.rb # module Puppet::Parser::Functions - newfunction(:validate_re, :doc => <<-DOC + newfunction(:validate_re, doc: <<-DOC @summary Perform simple validation of a string against one or more regular expressions. The first argument of this function should be a string to test, and the second argument should be a stringified regular expression (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. @return validation of a string against one or more regular expressions. @example **Usage** The following strings will validate against the regular expressions: validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) The following strings will fail to validate, causing compilation to abort: validate_re('one', [ '^two', '^three' ]) A helpful error message can be returned like this: validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') > *Note:* Compilation will also abort, if the first argument is not a String. Always use quotes to force stringification: validate_re("${::operatingsystemmajrelease}", '^[57]$') DOC - ) do |args| + ) do |args| function_deprecation([:validate_re, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Re. There is further documentation for validate_legacy function in the README.']) if (args.length < 2) || (args.length > 3) raise Puppet::ParseError, "validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)" end raise Puppet::ParseError, "validate_re(): input needs to be a String, not a #{args[0].class}" unless args[0].is_a? String msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" # We're using a flattened array here because we can't call String#any? in # Ruby 1.9 like we can in Ruby 1.8 raise Puppet::ParseError, msg unless [args[1]].flatten.any? do |re_str| args[0] =~ Regexp.compile(re_str) end end end diff --git a/lib/puppet/parser/functions/validate_slength.rb b/lib/puppet/parser/functions/validate_slength.rb index 32ee571..c7d5bb6 100644 --- a/lib/puppet/parser/functions/validate_slength.rb +++ b/lib/puppet/parser/functions/validate_slength.rb @@ -1,75 +1,75 @@ # frozen_string_literal: true # # validate_slength.rb # module Puppet::Parser::Functions - newfunction(:validate_slength, :doc => <<-DOC + newfunction(:validate_slength, doc: <<-DOC @summary Validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. An optional third parameter can be given the minimum length. It fails if the first argument is not a string or array of strings, and if arg 2 and arg 3 are not convertable to a number. @return validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. Fail compilation if any of the checks fail. @example **Usage** The following values will pass: validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) validate_slength(["discombobulate","moo"],17,3) The following valueis will not: validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) validate_slength(["discombobulate","moo"],17,10) DOC - ) do |args| + ) do |args| function_deprecation([:validate_slength, 'This method is deprecated, please use the stdlib validate_legacy function, with String[]. There is further documentation for validate_legacy function in the README.']) raise Puppet::ParseError, "validate_slength(): Wrong number of arguments (#{args.length}; must be 2 or 3)" unless args.length == 2 || args.length == 3 input, max_length, min_length = *args begin max_length = Integer(max_length) raise ArgumentError if max_length <= 0 rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected second argument to be a positive Numeric, got #{max_length}:#{max_length.class}" end if min_length begin min_length = Integer(min_length) raise ArgumentError if min_length < 0 rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected third argument to be unset or a positive Numeric, got #{min_length}:#{min_length.class}" end else min_length = 0 end raise Puppet::ParseError, 'validate_slength(): Expected second argument to be equal to or larger than third argument' unless max_length >= min_length validator = ->(str) do unless str.length <= max_length && str.length >= min_length raise Puppet::ParseError, "validate_slength(): Expected length of #{input.inspect} to be between #{min_length} and #{max_length}, was #{input.length}" end end case input when String validator.call(input) when Array input.each_with_index do |arg, pos| raise Puppet::ParseError, "validate_slength(): Expected element at array position #{pos} to be a String, got #{arg.class}" unless arg.is_a? String validator.call(arg) end else raise Puppet::ParseError, "validate_slength(): Expected first argument to be a String or Array, got #{input.class}" end end end diff --git a/lib/puppet/parser/functions/validate_string.rb b/lib/puppet/parser/functions/validate_string.rb index d490c61..6dd9634 100644 --- a/lib/puppet/parser/functions/validate_string.rb +++ b/lib/puppet/parser/functions/validate_string.rb @@ -1,49 +1,49 @@ # frozen_string_literal: true # # validate_String.rb # module Puppet::Parser::Functions - newfunction(:validate_string, :doc => <<-DOC + newfunction(:validate_string, doc: <<-DOC @summary Validate that all passed values are string data structures @return Validate that all passed values are string data structures. Failed compilation if any value fails this check. @example **Usage** The following values will pass: $my_string = "one two" validate_string($my_string, 'three') The following values will fail, causing compilation to abort: validate_string(true) validate_string([ 'some', 'array' ]) > *Note:* Validate_string(undef) will not fail in this version of the functions API (incl. current and future parser). Instead, use: ``` if $var == undef { fail('...') } ``` DOC - ) do |args| + ) do |args| function_deprecation([:validate_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_string(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # when called through the v4 API shim, undef gets translated to nil unless arg.is_a?(String) || arg.nil? raise Puppet::ParseError, "#{arg.inspect} is not a string. It looks to be a #{arg.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb b/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb index ca07e1a..a62ba37 100644 --- a/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb +++ b/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb @@ -1,52 +1,51 @@ # frozen_string_literal: true # # validate_x509_rsa_key_pair.rb # module Puppet::Parser::Functions - newfunction(:validate_x509_rsa_key_pair, :doc => <<-DOC + newfunction(:validate_x509_rsa_key_pair, doc: <<-DOC @summary Validates a PEM-formatted X.509 certificate and RSA private key using OpenSSL. Verifies that the certficate's signature was created from the supplied key. @return Fail compilation if any value fails this check. ```validate_x509_rsa_key_pair($cert, $key)``` DOC - ) do |args| - + ) do |args| require 'openssl' NUM_ARGS = 2 unless defined? NUM_ARGS unless args.length == NUM_ARGS raise Puppet::ParseError, "validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end end begin cert = OpenSSL::X509::Certificate.new(args[0]) rescue OpenSSL::X509::CertificateError => e raise Puppet::ParseError, "Not a valid x509 certificate: #{e}" end begin key = OpenSSL::PKey::RSA.new(args[1]) rescue OpenSSL::PKey::RSAError => e raise Puppet::ParseError, "Not a valid RSA key: #{e}" end unless cert.verify(key) raise Puppet::ParseError, 'Certificate signature does not match supplied key' end end end diff --git a/lib/puppet/parser/functions/values.rb b/lib/puppet/parser/functions/values.rb index f82615c..a47fe52 100644 --- a/lib/puppet/parser/functions/values.rb +++ b/lib/puppet/parser/functions/values.rb @@ -1,45 +1,44 @@ # frozen_string_literal: true # # values.rb # module Puppet::Parser::Functions - newfunction(:values, :type => :rvalue, :doc => <<-DOC + newfunction(:values, type: :rvalue, doc: <<-DOC @summary When given a hash this function will return the values of that hash. @return array of values @example **Usage** $hash = { 'a' => 1, 'b' => 2, 'c' => 3, } values($hash) This example would return: ```[1,2,3]``` > *Note:* From Puppet 5.5.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'values(): Requires hash to work with') end result = hash.values return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/values_at.rb b/lib/puppet/parser/functions/values_at.rb index 530d65d..29301b8 100644 --- a/lib/puppet/parser/functions/values_at.rb +++ b/lib/puppet/parser/functions/values_at.rb @@ -1,101 +1,100 @@ # frozen_string_literal: true # # values_at.rb # module Puppet::Parser::Functions - newfunction(:values_at, :type => :rvalue, :doc => <<-DOC + newfunction(:values_at, type: :rvalue, doc: <<-DOC @summary Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above @return an array of values identified by location @example **Usage** values_at(['a','b','c'], 2) Would return ['c'] values_at(['a','b','c'], ["0-1"]) Would return ['a','b'] values_at(['a','b','c','d','e'], [0, "2-3"]) Would return ['a','c','d'] > *Note:* Since Puppet 4.0.0 it is possible to slice an array with index and count directly in the language. A negative value is taken to be "from the end" of the array: `['a', 'b', 'c', 'd'][1, 2]` results in `['b', 'c']` `['a', 'b', 'c', 'd'][2, -1]` results in `['c', 'd']` `['a', 'b', 'c', 'd'][1, -2]` results in `['b', 'c']` DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "values_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments.shift unless array.is_a?(Array) raise(Puppet::ParseError, 'values_at(): Requires array to work with') end indices = [arguments.shift].flatten # Get them all ... Pokemon ... if !indices || indices.empty? raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect') end indices_list = [] indices.each do |i| i = i.to_s m = i.match(%r{^(\d+)(\.\.\.?|\-)(\d+)$}) if m start = m[1].to_i stop = m[3].to_i type = m[2] raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index') if start > stop raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size') if stop > array.size - 1 # First element is at index 0 is it not? range = case type when %r{^(\.\.|\-)$} then (start..stop) when %r{^(\.\.\.)$} then (start...stop) # Exclusive of last element ... end range.each { |i| indices_list << i.to_i } # rubocop:disable Lint/ShadowingOuterLocalVariable : Value is meant to be shadowed else # Only positive numbers allowed in this case ... - unless i =~ %r{^\d+$} + unless %r{^\d+$}.match?(i) raise(Puppet::ParseError, 'values_at(): Unknown format of given index') end # In Puppet numbers are often string-encoded ... i = i.to_i if i > array.size - 1 # Same story. First element is at index 0 ... raise(Puppet::ParseError, 'values_at(): Given index exceeds array size') end indices_list << i end end # We remove nil values as they make no sense in Puppet DSL ... result = indices_list.map { |i| array[i] }.compact return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/zip.rb b/lib/puppet/parser/functions/zip.rb index 55c0e5d..1006183 100644 --- a/lib/puppet/parser/functions/zip.rb +++ b/lib/puppet/parser/functions/zip.rb @@ -1,39 +1,38 @@ # frozen_string_literal: true # # zip.rb # module Puppet::Parser::Functions - newfunction(:zip, :type => :rvalue, :doc => <<-DOC + newfunction(:zip, type: :rvalue, doc: <<-DOC @summary Takes one element from first array and merges corresponding elements from second array. @return This generates a sequence of n-element arrays, where n is one more than the count of arguments. @example zip(['1','2','3'],['4','5','6']) Would result in: ["1", "4"], ["2", "5"], ["3", "6"] DOC - ) do |arguments| - + ) do |arguments| # Technically we support three arguments but only first is mandatory ... raise(Puppet::ParseError, "zip(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 a = arguments[0] b = arguments[1] unless a.is_a?(Array) && b.is_a?(Array) raise(Puppet::ParseError, 'zip(): Requires array to work with') end flatten = function_str2bool([arguments[2]]) if arguments[2] result = a.zip(b) result = flatten ? result.flatten : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb index b37cdb1..9fb281c 100644 --- a/lib/puppet/provider/file_line/ruby.rb +++ b/lib/puppet/provider/file_line/ruby.rb @@ -1,182 +1,182 @@ # frozen_string_literal: true Puppet::Type.type(:file_line).provide(:ruby) do desc <<-DOC @summary This type allows puppet to manage small config files. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will append the line to the end of the file to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. DOC def exists? found = false lines_count = 0 lines.each do |line| found = line.chomp == resource[:line] if found lines_count += 1 end end return found = lines_count > 0 if resource[:match].nil? match_count = count_matches(new_match_regex) found = if resource[:ensure] == :present if match_count.zero? if lines_count.zero? && resource[:append_on_no_match].to_s == 'false' true # lies, but gets the job done elsif lines_count.zero? && resource[:append_on_no_match].to_s != 'false' false else true end elsif resource[:replace_all_matches_not_matching_line].to_s == 'true' false # maybe lies, but knows there's still work to do elsif lines_count.zero? resource[:replace].to_s == 'false' else true end elsif match_count.zero? if lines_count.zero? false else true end elsif lines_count.zero? resource[:match_for_absence].to_s == 'true' else true end end def create return if resource[:replace].to_s != 'true' && count_matches(new_match_regex) > 0 if resource[:match] handle_create_with_match elsif resource[:after] handle_create_with_after else handle_append_line end end def destroy if resource[:match_for_absence].to_s == 'true' && resource[:match] handle_destroy_with_match else handle_destroy_line end end private def lines # If this type is ever used with very large files, we should # write this in a different way, using a temp # file; for now assuming that this type is only used on # small-ish config files that can fit into memory without # too much trouble. - @lines ||= File.readlines(resource[:path], :encoding => resource[:encoding]) + @lines ||= File.readlines(resource[:path], encoding: resource[:encoding]) rescue TypeError => _e # Ruby 1.8 doesn't support open_args @lines ||= File.readlines(resource[:path]) end def new_after_regex resource[:after] ? Regexp.new(resource[:after]) : nil end def new_match_regex resource[:match] ? Regexp.new(resource[:match]) : nil end def count_matches(regex) lines.select { |line| if resource[:replace_all_matches_not_matching_line].to_s == 'true' line.match(regex) unless line.chomp == resource[:line] else line.match(regex) end }.size end def handle_create_with_match after_regex = new_after_regex match_regex = new_match_regex match_count = count_matches(new_match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(match_regex.match(line) ? resource[:line] : line) next unless match_count.zero? && after_regex if after_regex.match(line) fh.puts(resource[:line]) match_count += 1 # Increment match_count to indicate that the new line has been inserted. end end if match_count.zero? fh.puts(resource[:line]) end end end def handle_create_with_after after_regex = new_after_regex after_count = count_matches(after_regex) if after_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "#{after_count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(line) if after_regex.match(line) fh.puts(resource[:line]) end end if after_count.zero? fh.puts(resource[:line]) end end end def handle_destroy_with_match match_regex = new_match_regex match_count = count_matches(match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end local_lines = lines File.open(resource[:path], 'w') do |fh| fh.write(local_lines.reject { |line| match_regex.match(line) }.join('')) end end def handle_destroy_line local_lines = lines File.open(resource[:path], 'w') do |fh| fh.write(local_lines.reject { |line| line.chomp == resource[:line] }.join('')) end end def handle_append_line local_lines = lines File.open(resource[:path], 'w') do |fh| local_lines.each do |line| fh.puts(line) end fh.puts(resource[:line]) end end end diff --git a/lib/puppet/type/file_line.rb b/lib/puppet/type/file_line.rb index 6a6168c..00a6512 100644 --- a/lib/puppet/type/file_line.rb +++ b/lib/puppet/type/file_line.rb @@ -1,205 +1,205 @@ # frozen_string_literal: true Puppet::Type.newtype(:file_line) do desc <<-DOC @summary Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will append the line to the end of the file to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. * Ensure Example ``` file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } ``` In this example, Puppet will ensure both of the specified lines are contained in the file /etc/sudoers. * Match Example ``` file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', } ``` In this code example match will look for a line beginning with export followed by HTTP_PROXY and replace it with the value in line. * Examples With `ensure => absent`: This type has two behaviors when `ensure => absent` is set. One possibility is to set `match => ...` and `match_for_absence => true`, as in the following example: ``` file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } ``` In this code example match will look for a line beginning with export followed by HTTP_PROXY and delete it. If multiple lines match, an error will be raised unless the `multiple => true` parameter is set. Note that the `line => ...` parameter would be accepted BUT IGNORED in the above example. The second way of using `ensure => absent` is to specify a `line => ...`, and no match: ``` file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', } ``` > *Note:* When ensuring lines are absent this way, the default behavior this time is to always remove all lines matching, and this behavior can't be disabled. * Encoding example: ``` file_line { "XScreenSaver": ensure => present, path => '/root/XScreenSaver', line => "*lock: 10:00:00", match => '^*lock:', encoding => "iso-8859-1", } ``` Files with special characters that are not valid UTF-8 will give the error message "invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify the correct encoding using the encoding attribute, the value of which needs to be a valid Ruby character encoding. **Autorequires:** If Puppet is managing the file that will contain the line being managed, the file_line resource will autorequire that file. DOC ensurable do desc 'Manage the state of this type.' defaultvalues defaultto :present end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:match) do desc 'An optional ruby regular expression to run against existing lines in the file. If a match is found, we replace that line rather than adding a new line. A regex comparison is performed against the line value and if it does not match an exception will be raised.' end newparam(:match_for_absence) do desc 'An optional value to determine if match should be applied when ensure => absent. If set to true and match is set, the line that matches match will be deleted. If set to false (the default), match is ignored when ensure => absent. When `ensure => present`, match_for_absence is ignored.' newvalues(true, false) defaultto false end newparam(:multiple) do desc 'An optional value to determine if match can change multiple lines. If set to false, an exception will be raised if more than one line matches' newvalues(true, false) end newparam(:after) do desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place) This is also takes a regex.' end # The line property never changes; the type only ever performs a create() or # destroy(). line is a property in order to allow it to correctly handle # Sensitive type values. Because it is a property which will never change, # it should never be considered out of sync. newproperty(:line) do desc 'The line to be appended to the file or used to replace matches found by the match attribute.' def retrieve @resource[:line] end end newparam(:path) do desc 'The file Puppet will ensure contains the line specified by the line parameter.' validate do |value| unless Puppet::Util.absolute_path?(value) raise Puppet::Error, "File paths must be fully qualified, not '#{value}'" end end end newparam(:replace) do desc 'If true, replace line that matches. If false, do not write line if a match is found' newvalues(true, false) defaultto true end newparam(:replace_all_matches_not_matching_line) do desc 'Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file.' newvalues(true, false) defaultto false end newparam(:encoding) do desc 'For files that are not UTF-8 encoded, specify encoding such as iso-8859-1' defaultto 'UTF-8' end newparam(:append_on_no_match) do desc 'If true, append line if match is not found. If false, do not append line if a match is not found' newvalues(true, false) defaultto true end # Autorequire the file resource if it's being managed autorequire(:file) do self[:path] end validate do if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:multiple].to_s == 'false' raise(Puppet::Error, 'multiple must be true when replace_all_matches_not_matching_line is true') end if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:replace].to_s == 'false' raise(Puppet::Error, 'replace must be true when replace_all_matches_not_matching_line is true') end unless self[:line] unless (self[:ensure].to_s == 'absent') && (self[:match_for_absence].to_s == 'true') && self[:match] raise(Puppet::Error, 'line is a required attribute') end end unless self[:path] raise(Puppet::Error, 'path is a required attribute') end end end diff --git a/spec/functions/any2bool_spec.rb b/spec/functions/any2bool_spec.rb index 0fd6c76..ff06a68 100644 --- a/spec/functions/any2bool_spec.rb +++ b/spec/functions/any2bool_spec.rb @@ -1,43 +1,43 @@ # frozen_string_literal: true require 'spec_helper' describe 'any2bool' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true).and_return(true) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('1.5').and_return(true) } describe 'when testing stringy values that mean "true"' do ['TRUE', '1', 't', 'y', 'true', 'yes'].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing stringy values that mean "false"' do ['FALSE', '', '0', 'f', 'n', 'false', 'no', 'undef', 'undefined', nil, :undef].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'when testing numeric values that mean "true"' do [1, '1', 1.5, '1.5'].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing numeric that mean "false"' do [-1, '-1', -1.5, '-1.5', '0', 0].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'everything else returns true' do - [[], {}, ['1'], [1], { :one => 1 }].each do |value| + [[], {}, ['1'], [1], { one: 1 }].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end end diff --git a/spec/functions/camelcase_spec.rb b/spec/functions/camelcase_spec.rb index fd3264d..aa78fcb 100644 --- a/spec/functions/camelcase_spec.rb +++ b/spec/functions/camelcase_spec.rb @@ -1,19 +1,19 @@ # frozen_string_literal: true require 'spec_helper' -describe 'camelcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'camelcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('abc').and_return('Abc') } it { is_expected.to run.with_params('aa_bb_cc').and_return('AaBbCc') } it { is_expected.to run.with_params('_aa__bb__cc_').and_return('AaBbCc') } it { is_expected.to run.with_params('100').and_return('100') } it { is_expected.to run.with_params('1_00').and_return('100') } it { is_expected.to run.with_params('_').and_return('') } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['abc', 'aa_bb_cc']).and_return(['Abc', 'AaBbCc']) } it { is_expected.to run.with_params(['abc', 1, 'aa_bb_cc']).and_return(['Abc', 1, 'AaBbCc']) } end diff --git a/spec/functions/capitalize_spec.rb b/spec/functions/capitalize_spec.rb index ed93cc5..f67c8be 100644 --- a/spec/functions/capitalize_spec.rb +++ b/spec/functions/capitalize_spec.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true require 'spec_helper' -describe 'capitalize', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'capitalize', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('One') } it { is_expected.to run.with_params('one two').and_return('One two') } it { is_expected.to run.with_params('ONE TWO').and_return('One two') } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('One') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one', 'two']).and_return(['One', 'Two']) } it { is_expected.to run.with_params(['one', 1, 'two']).and_return(['One', 1, 'Two']) } end diff --git a/spec/functions/ceiling_spec.rb b/spec/functions/ceiling_spec.rb index 7f9b298..5e5f34c 100644 --- a/spec/functions/ceiling_spec.rb +++ b/spec/functions/ceiling_spec.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true require 'spec_helper' -describe 'ceiling', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'ceiling', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{Wrong argument type given}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong argument type given}) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } it { is_expected.to run.with_params(33.1).and_return(34) } it { is_expected.to run.with_params(-33.1).and_return(-33) } it { is_expected.to run.with_params('33.1').and_return(34) } end diff --git a/spec/functions/chomp_spec.rb b/spec/functions/chomp_spec.rb index 8cc567a..68b7cd3 100644 --- a/spec/functions/chomp_spec.rb +++ b/spec/functions/chomp_spec.rb @@ -1,29 +1,29 @@ # frozen_string_literal: true require 'spec_helper' -describe 'chomp', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'chomp', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments given}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string}) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } it { is_expected.to run.with_params(["one\n", 'two', "three\n"]).and_return(['one', 'two', 'three']) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(['one', 'two', 'three']) } it { is_expected.to run.with_params([1, 2, 3]).and_return([1, 2, 3]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end diff --git a/spec/functions/chop_spec.rb b/spec/functions/chop_spec.rb index 0b37d4e..2cbccd1 100644 --- a/spec/functions/chop_spec.rb +++ b/spec/functions/chop_spec.rb @@ -1,29 +1,29 @@ # frozen_string_literal: true require 'spec_helper' -describe 'chop', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'chop', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either an array or string}) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('on') } it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } it { is_expected.to run.with_params(["one\n", 'two', "three\n"]).and_return(['one', 'tw', 'three']) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('on') } it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(['one', 'tw', 'three']) } it { is_expected.to run.with_params([1, 2, 3]).and_return([1, 2, 3]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end diff --git a/spec/functions/downcase_spec.rb b/spec/functions/downcase_spec.rb index 641b8c5..07c6374 100644 --- a/spec/functions/downcase_spec.rb +++ b/spec/functions/downcase_spec.rb @@ -1,17 +1,17 @@ # frozen_string_literal: true require 'spec_helper' -describe 'downcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'downcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError, %r{Requires either array or string}) } it { is_expected.to run.with_params('abc').and_return('abc') } it { is_expected.to run.with_params('Abc').and_return('abc') } it { is_expected.to run.with_params('ABC').and_return('abc') } it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('abc') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['ONE', 'TWO']).and_return(['one', 'two']) } it { is_expected.to run.with_params(['One', 1, 'Two']).and_return(['one', 1, 'two']) } end diff --git a/spec/functions/empty_spec.rb b/spec/functions/empty_spec.rb index d4de734..5b0ba29 100644 --- a/spec/functions/empty_spec.rb +++ b/spec/functions/empty_spec.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true require 'spec_helper' -describe 'empty', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'empty', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(false).and_raise_error(Puppet::ParseError, %r{Requires either array, hash, string or integer}) } it { is_expected.to run.with_params(0).and_return(false) } it { is_expected.to run.with_params('').and_return(true) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(AlsoString.new('')).and_return(true) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return(false) } it { is_expected.to run.with_params([]).and_return(true) } it { is_expected.to run.with_params(['one']).and_return(false) } it { is_expected.to run.with_params({}).and_return(true) } it { is_expected.to run.with_params('key' => 'value').and_return(false) } end diff --git a/spec/functions/flatten_spec.rb b/spec/functions/flatten_spec.rb index 70503dd..365535b 100644 --- a/spec/functions/flatten_spec.rb +++ b/spec/functions/flatten_spec.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true require 'spec_helper' -describe 'flatten', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'flatten', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires array}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Requires array}) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params([['one']]).and_return(['one']) } it { is_expected.to run.with_params(['a', 'b', 'c', 'd', 'e', 'f', 'g']).and_return(['a', 'b', 'c', 'd', 'e', 'f', 'g']) } it { is_expected.to run.with_params([['a', 'b', ['c', ['d', 'e'], 'f', 'g']]]).and_return(['a', 'b', 'c', 'd', 'e', 'f', 'g']) } it { is_expected.to run.with_params(['ã', 'β', ['ĉ', ['đ', 'ẽ', 'ƒ', 'ġ']]]).and_return(['ã', 'β', 'ĉ', 'đ', 'ẽ', 'ƒ', 'ġ']) } end diff --git a/spec/functions/floor_spec.rb b/spec/functions/floor_spec.rb index 13da9e0..fe45142 100644 --- a/spec/functions/floor_spec.rb +++ b/spec/functions/floor_spec.rb @@ -1,15 +1,15 @@ # frozen_string_literal: true require 'spec_helper' -describe 'floor', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'floor', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{Wrong argument type}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong argument type}) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } it { is_expected.to run.with_params(33.1).and_return(33) } it { is_expected.to run.with_params(-33.1).and_return(-34) } end diff --git a/spec/functions/fqdn_rand_string_spec.rb b/spec/functions/fqdn_rand_string_spec.rb index 125ee5a..1102b87 100644 --- a/spec/functions/fqdn_rand_string_spec.rb +++ b/spec/functions/fqdn_rand_string_spec.rb @@ -1,69 +1,69 @@ # frozen_string_literal: true require 'spec_helper' describe 'fqdn_rand_string' do let(:default_charset) { %r{\A[a-zA-Z0-9]{100}\z} } it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1.5).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(-10).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('-10').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('string').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params([]).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params({}).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(100).and_return(default_charset) } it { is_expected.to run.with_params('100').and_return(default_charset) } it { is_expected.to run.with_params(100, nil).and_return(default_charset) } it { is_expected.to run.with_params(100, '').and_return(default_charset) } it { is_expected.to run.with_params(100, 'a').and_return(%r{\Aa{100}\z}) } it { is_expected.to run.with_params(100, 'ab').and_return(%r{\A[ab]{100}\z}) } it { is_expected.to run.with_params(100, 'ãβ').and_return(%r{\A[ãβ]{100}\z}) } it "provides the same 'random' value on subsequent calls for the same host" do expect(fqdn_rand_string(10)).to eql(fqdn_rand_string(10)) end it 'considers the same host and same extra arguments to have the same random sequence' do - first_random = fqdn_rand_string(10, :extra_identifier => [1, 'same', 'host']) - second_random = fqdn_rand_string(10, :extra_identifier => [1, 'same', 'host']) + first_random = fqdn_rand_string(10, extra_identifier: [1, 'same', 'host']) + second_random = fqdn_rand_string(10, extra_identifier: [1, 'same', 'host']) expect(first_random).to eql(second_random) end it 'allows extra arguments to control the random value on a single host' do - first_random = fqdn_rand_string(10, :extra_identifier => [1, 'different', 'host']) - second_different_random = fqdn_rand_string(10, :extra_identifier => [2, 'different', 'host']) + first_random = fqdn_rand_string(10, extra_identifier: [1, 'different', 'host']) + second_different_random = fqdn_rand_string(10, extra_identifier: [2, 'different', 'host']) expect(first_random).not_to eql(second_different_random) end it 'returns different strings for different hosts' do - val1 = fqdn_rand_string(10, :host => 'first.host.com') - val2 = fqdn_rand_string(10, :host => 'second.host.com') + val1 = fqdn_rand_string(10, host: 'first.host.com') + val2 = fqdn_rand_string(10, host: 'second.host.com') expect(val1).not_to eql(val2) end def fqdn_rand_string(max, args = {}) host = args[:host] || '127.0.0.1' charset = args[:charset] extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn', {}).and_return(host) function_args = [max] if args.key?(:charset) || !extra.empty? function_args << charset end function_args += extra scope.function_fqdn_rand_string(function_args) end end diff --git a/spec/functions/fqdn_rotate_spec.rb b/spec/functions/fqdn_rotate_spec.rb index 4027f90..8c68c37 100644 --- a/spec/functions/fqdn_rotate_spec.rb +++ b/spec/functions/fqdn_rotate_spec.rb @@ -1,76 +1,76 @@ # frozen_string_literal: true require 'spec_helper' describe 'fqdn_rotate' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('ã').and_return('ã') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it 'rotates a string and the result should be the same size' do expect(fqdn_rotate('asdf').size).to eq(4) end it 'rotates a string to give the same results for one host' do - val1 = fqdn_rotate('abcdefg', :host => 'one') - val2 = fqdn_rotate('abcdefg', :host => 'one') + val1 = fqdn_rotate('abcdefg', host: 'one') + val2 = fqdn_rotate('abcdefg', host: 'one') expect(val1).to eq(val2) end it 'allows extra arguments to control the random rotation on a single host' do - val1 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'different', 'host']) - val2 = fqdn_rotate('abcdefg', :extra_identifier => [2, 'different', 'host']) + val1 = fqdn_rotate('abcdefg', extra_identifier: [1, 'different', 'host']) + val2 = fqdn_rotate('abcdefg', extra_identifier: [2, 'different', 'host']) expect(val1).not_to eq(val2) end it 'considers the same host and same extra arguments to have the same random rotation' do - val1 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'same', 'host']) - val2 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'same', 'host']) + val1 = fqdn_rotate('abcdefg', extra_identifier: [1, 'same', 'host']) + val2 = fqdn_rotate('abcdefg', extra_identifier: [1, 'same', 'host']) expect(val1).to eq(val2) end it 'rotates a string to give different values on different hosts' do - val1 = fqdn_rotate('abcdefg', :host => 'one') - val2 = fqdn_rotate('abcdefg', :host => 'two') + val1 = fqdn_rotate('abcdefg', host: 'one') + val2 = fqdn_rotate('abcdefg', host: 'two') expect(val1).not_to eq(val2) end it 'accepts objects which extend String' do result = fqdn_rotate(AlsoString.new('asdf')) expect(result).to eq('dfas') end it 'uses the Puppet::Util.deterministic_rand function' do skip 'Puppet::Util#deterministic_rand not available' unless Puppet::Util.respond_to?(:deterministic_rand) expect(Puppet::Util).to receive(:deterministic_rand).with(44_489_829_212_339_698_569_024_999_901_561_968_770, 4) fqdn_rotate('asdf') end it 'does not leave the global seed in a deterministic state' do fqdn_rotate('asdf') rand1 = rand fqdn_rotate('asdf') rand2 = rand expect(rand1).not_to eql(rand2) end def fqdn_rotate(value, args = {}) host = args[:host] || '127.0.0.1' extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn').and_return(host) function_args = [value] + extra scope.function_fqdn_rotate(function_args) end end diff --git a/spec/functions/getvar_spec.rb b/spec/functions/getvar_spec.rb index 6d506f5..94af518 100644 --- a/spec/functions/getvar_spec.rb +++ b/spec/functions/getvar_spec.rb @@ -1,47 +1,47 @@ # frozen_string_literal: true require 'spec_helper' describe 'getvar' do it { is_expected.not_to eq(nil) } - describe 'before Puppet 6.0.0', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do + describe 'before Puppet 6.0.0', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end - describe 'from Puppet 6.0.0', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') >= 0 do + describe 'from Puppet 6.0.0', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') >= 0 do it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects between 1 and 2 arguments, got none}i) } it { is_expected.to run.with_params('one', 'two').and_return('two') } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(ArgumentError, %r{expects between 1 and 2 arguments, got 3}i) } end it { is_expected.to run.with_params('::foo').and_return(nil) } context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::data { $foo = 'baz' } include site::data PUPPETCODE end it { is_expected.to run.with_params('site::data::foo').and_return('baz') } it { is_expected.to run.with_params('::site::data::foo').and_return('baz') } it { is_expected.to run.with_params('::site::data::bar').and_return(nil) } end context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::info { $lock = 'ŧҺîš íš ắ śţřĭŋĝ' } class site::new { $item = '万Ü€‰' } include site::info include site::new PUPPETCODE end it { is_expected.to run.with_params('site::info::lock').and_return('ŧҺîš íš ắ śţřĭŋĝ') } it { is_expected.to run.with_params('::site::new::item').and_return('万Ü€‰') } end end diff --git a/spec/functions/has_interface_with_spec.rb b/spec/functions/has_interface_with_spec.rb index a4024d5..d55f58e 100644 --- a/spec/functions/has_interface_with_spec.rb +++ b/spec/functions/has_interface_with_spec.rb @@ -1,41 +1,41 @@ # frozen_string_literal: true require 'spec_helper' describe 'has_interface_with' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } # We need to mock out the Facts so we can specify how we expect this function # to behave on different platforms. context 'when on Mac OS X Systems' do - let(:facts) { { :interfaces => 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } + let(:facts) { { interfaces: 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } it { is_expected.to run.with_params('lo0').and_return(true) } it { is_expected.to run.with_params('lo').and_return(false) } end context 'when on Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :ipaddress => '10.0.0.1', - :ipaddress_lo => '127.0.0.1', - :ipaddress_eth0 => '10.0.0.1', - :muppet => 'kermit', - :muppet_lo => 'mspiggy', - :muppet_eth0 => 'kermit', + interfaces: 'eth0,lo', + ipaddress: '10.0.0.1', + ipaddress_lo: '127.0.0.1', + ipaddress_eth0: '10.0.0.1', + muppet: 'kermit', + muppet_lo: 'mspiggy', + muppet_eth0: 'kermit', } end it { is_expected.to run.with_params('lo').and_return(true) } it { is_expected.to run.with_params('lo0').and_return(false) } it { is_expected.to run.with_params('ipaddress', '127.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '10.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '8.8.8.8').and_return(false) } it { is_expected.to run.with_params('muppet', 'kermit').and_return(true) } it { is_expected.to run.with_params('muppet', 'mspiggy').and_return(true) } it { is_expected.to run.with_params('muppet', 'bigbird').and_return(false) } end end diff --git a/spec/functions/has_ip_address_spec.rb b/spec/functions/has_ip_address_spec.rb index 577106f..a30a5a5 100644 --- a/spec/functions/has_ip_address_spec.rb +++ b/spec/functions/has_ip_address_spec.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true require 'spec_helper' describe 'has_ip_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when on Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :ipaddress => '10.0.0.1', - :ipaddress_lo => '127.0.0.1', - :ipaddress_eth0 => '10.0.0.1', + interfaces: 'eth0,lo', + ipaddress: '10.0.0.1', + ipaddress_lo: '127.0.0.1', + ipaddress_eth0: '10.0.0.1', } end it { is_expected.to run.with_params('127.0.0.1').and_return(true) } it { is_expected.to run.with_params('10.0.0.1').and_return(true) } it { is_expected.to run.with_params('8.8.8.8').and_return(false) } it { is_expected.to run.with_params('invalid').and_return(false) } end end diff --git a/spec/functions/has_ip_network_spec.rb b/spec/functions/has_ip_network_spec.rb index 13a8606..3366757 100644 --- a/spec/functions/has_ip_network_spec.rb +++ b/spec/functions/has_ip_network_spec.rb @@ -1,24 +1,24 @@ # frozen_string_literal: true require 'spec_helper' describe 'has_ip_network' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when on Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :network_lo => '127.0.0.0', - :network_eth0 => '10.0.0.0', + interfaces: 'eth0,lo', + network_lo: '127.0.0.0', + network_eth0: '10.0.0.0', } end it { is_expected.to run.with_params('127.0.0.0').and_return(true) } it { is_expected.to run.with_params('10.0.0.0').and_return(true) } it { is_expected.to run.with_params('8.8.8.0').and_return(false) } it { is_expected.to run.with_params('invalid').and_return(false) } end end diff --git a/spec/functions/is_domain_name_spec.rb b/spec/functions/is_domain_name_spec.rb index 4dd35b2..a022140 100644 --- a/spec/functions/is_domain_name_spec.rb +++ b/spec/functions/is_domain_name_spec.rb @@ -1,51 +1,51 @@ # frozen_string_literal: true require 'spec_helper' describe 'is_domain_name' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('.').and_return(true) } it { is_expected.to run.with_params('com').and_return(true) } it { is_expected.to run.with_params('com.').and_return(true) } it { is_expected.to run.with_params('x.com').and_return(true) } it { is_expected.to run.with_params('x.com.').and_return(true) } it { is_expected.to run.with_params('foo.example.com').and_return(true) } it { is_expected.to run.with_params('foo.example.com.').and_return(true) } it { is_expected.to run.with_params('2foo.example.com').and_return(true) } it { is_expected.to run.with_params('2foo.example.com.').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com.').and_return(true) } it { is_expected.to run.with_params(true).and_return(false) } describe 'inputs with spaces' do it { is_expected.to run.with_params('invalid domain').and_return(false) } end describe 'inputs with hyphens' do it { is_expected.to run.with_params('foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('foo-bar.example.com.').and_return(true) } it { is_expected.to run.with_params('www.foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('www.foo-bar.example.com.').and_return(true) } it { is_expected.to run.with_params('-foo.example.com').and_return(false) } it { is_expected.to run.with_params('-foo.example.com.').and_return(false) } end # Values obtained from Facter values will be frozen strings # in newer versions of Facter: - it { is_expected.to run.with_params('www.example.com'.freeze).and_return(true) } + it { is_expected.to run.with_params('www.example.com').and_return(true) } describe 'top level domain must be alphabetic if there are multiple labels' do it { is_expected.to run.with_params('2com').and_return(true) } it { is_expected.to run.with_params('www.example.2com').and_return(false) } end describe 'IP addresses are not domain names' do it { is_expected.to run.with_params('192.168.1.1').and_return(false) } end end diff --git a/spec/functions/is_ipv4_address_spec.rb b/spec/functions/is_ipv4_address_spec.rb index b4f691f..4298683 100644 --- a/spec/functions/is_ipv4_address_spec.rb +++ b/spec/functions/is_ipv4_address_spec.rb @@ -1,33 +1,33 @@ # frozen_string_literal: true require 'spec_helper' describe 'is_ipv4_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(true) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(false) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end end end diff --git a/spec/functions/is_ipv6_address_spec.rb b/spec/functions/is_ipv6_address_spec.rb index cf1d6fa..3917133 100644 --- a/spec/functions/is_ipv6_address_spec.rb +++ b/spec/functions/is_ipv6_address_spec.rb @@ -1,32 +1,32 @@ # frozen_string_literal: true require 'spec_helper' describe 'is_ipv6_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) } it { is_expected.to run.with_params('85a3:0000:0000:8a2e:0370:7334:100.100.100.100').and_return(true) } it { is_expected.to run.with_params('1.2.3').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334:ggg').and_return(false) } - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end end end diff --git a/spec/functions/join_spec.rb b/spec/functions/join_spec.rb index 117381e..2175248 100644 --- a/spec/functions/join_spec.rb +++ b/spec/functions/join_spec.rb @@ -1,22 +1,22 @@ # frozen_string_literal: true require 'spec_helper' -describe 'join', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'join', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the second.') is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Requires array to work with}) } it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{Requires string to work with}) } it { is_expected.to run.with_params([]).and_return('') } it { is_expected.to run.with_params([], ':').and_return('') } it { is_expected.to run.with_params(['one']).and_return('one') } it { is_expected.to run.with_params(['one'], ':').and_return('one') } it { is_expected.to run.with_params(['one', 'two', 'three']).and_return('onetwothree') } it { is_expected.to run.with_params(['one', 'two', 'three'], ':').and_return('one:two:three') } it { is_expected.to run.with_params(['ōŋể', 'ŧשợ', 'ţђŕẽё'], ':').and_return('ōŋể:ŧשợ:ţђŕẽё') } end diff --git a/spec/functions/keys_spec.rb b/spec/functions/keys_spec.rb index fb255e8..befc834 100644 --- a/spec/functions/keys_spec.rb +++ b/spec/functions/keys_spec.rb @@ -1,26 +1,26 @@ # frozen_string_literal: true require 'spec_helper' -describe 'keys', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'keys', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params({}).and_return([]) } it { is_expected.to run.with_params('key' => 'value').and_return(['key']) } it 'returns the array of keys' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }]) expect(result).to match_array(['key1', 'key2']) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'ҝểү' => '√ẳŀμệ', 'キー' => '値' }]) expect(result).to match_array(['ҝểү', 'キー']) end end diff --git a/spec/functions/length_spec.rb b/spec/functions/length_spec.rb index 20a387a..183a31c 100644 --- a/spec/functions/length_spec.rb +++ b/spec/functions/length_spec.rb @@ -1,33 +1,33 @@ # frozen_string_literal: true require 'spec_helper' -describe 'length', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'length', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'length' expects 1 argument, got none}) } it { is_expected.to run.with_params([], 'extra').and_raise_error(ArgumentError, %r{'length' expects 1 argument, got 2}) } it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Integer}) } it { is_expected.to run.with_params(true).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Boolean}) } it { is_expected.to run.with_params('1').and_return(1) } it { is_expected.to run.with_params('1.0').and_return(3) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(3) } it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } it { is_expected.to run.with_params('1' => '2').and_return(1) } it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } context 'when using a class extending String' do it { is_expected.to run.with_params(AlsoString.new('asdfghjkl')).and_return(9) } end end diff --git a/spec/functions/load_module_metadata_spec.rb b/spec/functions/load_module_metadata_spec.rb index 7fa2b63..caca5e7 100644 --- a/spec/functions/load_module_metadata_spec.rb +++ b/spec/functions/load_module_metadata_spec.rb @@ -1,53 +1,53 @@ # frozen_string_literal: true require 'spec_helper' describe 'load_module_metadata' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'when calling with valid arguments' do before :each do # In Puppet 7, there are two prior calls to File.read prior to the responses we want to mock allow(File).to receive(:read).with(anything, anything).and_call_original - allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') # Additional modules used by litmus which are identified while running these dues to being in fixtures - allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, :encoding => 'utf-8') + allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, encoding: 'utf-8') end context 'when calling with valid utf8 and double byte character arguments' do before :each do - allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') end let(:prefix) { 'C:' if Puppet::Util::Platform.windows? } it 'jsons parse the file' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(true) allow(File).to receive(:read).with("#{prefix}/path/to/module/metadata.json").and_return('{"name": "spencer-science"}') result = subject.execute('science') expect(result['name']).to eq('spencer-science') end it 'fails by default if there is no metadata.json' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) expect { subject.call(['science']) }.to raise_error(Puppet::ParseError) end it 'returns nil if user allows empty metadata.json' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) result = subject.execute('science', true) expect(result).to eq({}) end end end end diff --git a/spec/functions/loadjson_spec.rb b/spec/functions/loadjson_spec.rb index d745bf1..c45123c 100644 --- a/spec/functions/loadjson_spec.rb +++ b/spec/functions/loadjson_spec.rb @@ -1,148 +1,148 @@ # frozen_string_literal: true require 'spec_helper' describe 'loadjson' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } describe 'when calling with valid arguments' do before :each do # In Puppet 7, there are two prior calls to File.read prior to the responses we want to mock allow(File).to receive(:read).with(anything, anything).and_call_original - allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') # Additional modules used by litmus which are identified while running these dues to being in fixtures - allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, :encoding => 'utf-8') + allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, encoding: 'utf-8') end context 'when a non-existing file is specified' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesnotexist' else '/tmp/doesnotexist' end end before(:each) do allow(File).to receive(:exists?).with(filename).and_return(false).once allow(PSON).to receive(:load).never end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } it { is_expected.to run.with_params(filename, 'đẽƒằưļŧ' => '٧ẵłựέ').and_return('đẽƒằưļŧ' => '٧ẵłựέ') } it { is_expected.to run.with_params(filename, 'デフォルト' => '値').and_return('デフォルト' => '値') } end context 'when an existing file is specified' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).and_return(data).once end it { is_expected.to run.with_params(filename).and_return(data) } end context 'when the file could not be parsed' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:json) { '{"key":"value"}' } before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).once.and_raise StandardError, 'Something terrible have happened!' end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when an existing URL is specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username and password) is specified' do let(:filename) do 'https://user1:pass1@example.local/myhash.json' end let(:url_no_auth) { 'https://example.local/myhash.json' } - let(:basic_auth) { { :http_basic_authentication => ['user1', 'pass1'] } } + let(:basic_auth) { { http_basic_authentication: ['user1', 'pass1'] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username) is specified' do let(:filename) do 'https://user1@example.local/myhash.json' end let(:url_no_auth) { 'https://example.local/myhash.json' } - let(:basic_auth) { { :http_basic_authentication => ['user1', ''] } } + let(:basic_auth) { { http_basic_authentication: ['user1', ''] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when the URL output could not be parsed, with default specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:json) { ',;{"key":"value"}' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).once.and_raise StandardError, 'Something terrible have happened!' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when the URL does not exist, with default specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_raise OpenURI::HTTPError, '404 File not Found' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end end diff --git a/spec/functions/loadyaml_spec.rb b/spec/functions/loadyaml_spec.rb index cda3d60..4de82ec 100644 --- a/spec/functions/loadyaml_spec.rb +++ b/spec/functions/loadyaml_spec.rb @@ -1,103 +1,103 @@ # frozen_string_literal: true require 'spec_helper' describe 'loadyaml' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } context 'when a non-existing file is specified' do let(:filename) { '/tmp/doesnotexist' } it "'default' => 'value'" do expect(File).to receive(:exists?).with(filename).and_return(false).once expect(YAML).to receive(:load_file).never is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') end end context 'when an existing file is specified' do let(:filename) { '/tmp/doesexist' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it "returns 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'" do expect(File).to receive(:exists?).with(filename).and_return(true).once expect(YAML).to receive(:load_file).with(filename).and_return(data).once is_expected.to run.with_params(filename).and_return(data) end end context 'when the file could not be parsed' do let(:filename) { '/tmp/doesexist' } it 'filename /tmp/doesexist' do expect(File).to receive(:exists?).with(filename).and_return(true).once allow(YAML).to receive(:load_file).with(filename).once.and_raise(StandardError, 'Something terrible have happened!') is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') end end context 'when an existing URL is specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username and password) is specified' do let(:filename) { 'https://user1:pass1@example.local/myhash.yaml' } let(:url_no_auth) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['user1', 'pass1'] } } + let(:basic_auth) { { http_basic_authentication: ['user1', 'pass1'] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username) is specified' do let(:filename) { 'https://user1@example.local/myhash.yaml' } let(:url_no_auth) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['user1', ''] } } + let(:basic_auth) { { http_basic_authentication: ['user1', ''] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL could not be parsed, with default specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_raise StandardError, 'Cannot parse data' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when a URL does not exist, with default specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_raise OpenURI::HTTPError, '404 File not Found' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end diff --git a/spec/functions/lstrip_spec.rb b/spec/functions/lstrip_spec.rb index 4900379..ee82223 100644 --- a/spec/functions/lstrip_spec.rb +++ b/spec/functions/lstrip_spec.rb @@ -1,37 +1,37 @@ # frozen_string_literal: true require 'spec_helper' -describe 'lstrip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'lstrip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t one").and_return('one') } it { is_expected.to run.with_params('one ').and_return('one ') } it { is_expected.to run.with_params(' one ').and_return('one ') } it { is_expected.to run.with_params(' one ').and_return('one ') } it { is_expected.to run.with_params(' ǿňè ').and_return('ǿňè ') } it { is_expected.to run.with_params("\tone ").and_return('one ') } it { is_expected.to run.with_params("\t one ").and_return('one ') } it { is_expected.to run.with_params("one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params("\tone \t").and_return("one \t") } it { is_expected.to run.with_params("\t one \t").and_return("one \t") } it { is_expected.to run.with_params(' o n e ').and_return('o n e ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one ') } end diff --git a/spec/functions/max_spec.rb b/spec/functions/max_spec.rb index 552a3dc..b3868d7 100644 --- a/spec/functions/max_spec.rb +++ b/spec/functions/max_spec.rb @@ -1,23 +1,23 @@ # frozen_string_literal: true require 'spec_helper' -describe 'max', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'max', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(2) } it { is_expected.to run.with_params(1, 2, 3).and_return(3) } it { is_expected.to run.with_params(3, 2, 1).and_return(3) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('two') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('two') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('two') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return('one') } it { is_expected.to run.with_params('1', 'one').and_return('one') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.4e0') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.3e1) } end end diff --git a/spec/functions/min_spec.rb b/spec/functions/min_spec.rb index 110eebb..4b73012 100644 --- a/spec/functions/min_spec.rb +++ b/spec/functions/min_spec.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true require 'spec_helper' -describe 'min', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'min', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(1) } it { is_expected.to run.with_params(1, 2, 3).and_return(1) } it { is_expected.to run.with_params(3, 2, 1).and_return(1) } it { is_expected.to run.with_params(12, 8).and_return(8) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('one') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('one') } it { is_expected.to run.with_params('the', 'public', 'art', 'galleries').and_return('art') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return(1) } it { is_expected.to run.with_params('1', 'one').and_return('1') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.3e1') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.4e0) } end end diff --git a/spec/functions/os_version_gte_spec.rb b/spec/functions/os_version_gte_spec.rb index ecfb768..5de5838 100644 --- a/spec/functions/os_version_gte_spec.rb +++ b/spec/functions/os_version_gte_spec.rb @@ -1,47 +1,47 @@ # frozen_string_literal: true require 'spec_helper' describe 'os_version_gte' do context 'on Debian 9' do let(:facts) do { - :operatingsystem => 'Debian', - :operatingsystemmajrelease => '9', + operatingsystem: 'Debian', + operatingsystemmajrelease: '9', } end it { is_expected.to run.with_params('Debian', '9').and_return(true) } it { is_expected.to run.with_params('Debian', '8').and_return(false) } it { is_expected.to run.with_params('Debian', '8.0').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(false) } it { is_expected.to run.with_params('Fedora', '29').and_return(false) } end context 'on Ubuntu 16.04' do let(:facts) do { - :operatingsystem => 'Ubuntu', - :operatingsystemmajrelease => '16.04', + operatingsystem: 'Ubuntu', + operatingsystemmajrelease: '16.04', } end it { is_expected.to run.with_params('Debian', '9').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(true) } it { is_expected.to run.with_params('Ubuntu', '18.04').and_return(true) } it { is_expected.to run.with_params('Fedora', '29').and_return(false) } end context 'with invalid params' do let(:facts) do { - :operatingsystem => 'Ubuntu', - :operatingsystemmajrelease => '16.04', + operatingsystem: 'Ubuntu', + operatingsystemmajrelease: '16.04', } end it { is_expected.to run.with_params('123', 'abc').and_return(false) } it { is_expected.to run.with_params([], 123).and_raise_error(ArgumentError) } end end diff --git a/spec/functions/parsejson_spec.rb b/spec/functions/parsejson_spec.rb index 9d7eadc..bc8c2f7 100644 --- a/spec/functions/parsejson_spec.rb +++ b/spec/functions/parsejson_spec.rb @@ -1,68 +1,68 @@ # frozen_string_literal: true require 'spec_helper' describe 'parsejson' do it 'exists' do is_expected.not_to eq(nil) end it 'raises an error if called without any arguments' do is_expected.to run.with_params .and_raise_error(%r{wrong number of arguments}i) end context 'with correct JSON data' do it 'is able to parse JSON data with a Hash' do is_expected.to run.with_params('{"a":"1","b":"2"}') .and_return('a' => '1', 'b' => '2') end it 'is able to parse JSON data with an Array' do is_expected.to run.with_params('["a","b","c"]') .and_return(['a', 'b', 'c']) end it 'is able to parse empty JSON values' do actual_array = ['[]', '{}'] expected = [[], {}] actual_array.each_with_index do |actual, index| is_expected.to run.with_params(actual).and_return(expected[index]) end end it 'is able to parse JSON data with a mixed structure' do is_expected.to run.with_params('{"a":"1","b":2,"c":{"d":[true,false]}}') .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [true, false] }) end it 'is able to parse JSON data with a UTF8 and double byte characters' do is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}') .and_return('×' => 'これ', 'ý' => '記号', 'です' => { '©' => ['Á', 'ß'] }) end it 'does not return the default value if the data was parsed correctly' do is_expected.to run.with_params('{"a":"1"}', 'default_value') .and_return('a' => '1') end end context 'with incorrect JSON data' do it 'raises an error with invalid JSON and no default' do is_expected.to run.with_params('') .and_raise_error(PSON::ParserError) end it 'supports a structure for a default value' do is_expected.to run.with_params('', 'a' => '1') .and_return('a' => '1') end ['', 1, 1.2, nil, true, false, [], {}, :yaml].each do |value| - it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do + it "returns the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end end end diff --git a/spec/functions/parseyaml_spec.rb b/spec/functions/parseyaml_spec.rb index f9bbc29..f4ce419 100644 --- a/spec/functions/parseyaml_spec.rb +++ b/spec/functions/parseyaml_spec.rb @@ -1,76 +1,76 @@ # frozen_string_literal: true require 'spec_helper' describe 'parseyaml' do it 'exists' do is_expected.not_to eq(nil) end it 'raises an error if called without any arguments' do is_expected.to run.with_params .and_raise_error(%r{wrong number of arguments}i) end context 'with correct YAML data' do it 'is able to parse a YAML data with a String' do actual_array = ['--- just a string', 'just a string'] actual_array.each do |actual| is_expected.to run.with_params(actual).and_return('just a string') end end it 'is able to parse YAML data with a Hash' do is_expected.to run.with_params("---\na: '1'\nb: '2'\n") .and_return('a' => '1', 'b' => '2') end it 'is able to parse YAML data with an Array' do is_expected.to run.with_params("---\n- a\n- b\n- c\n") .and_return(['a', 'b', 'c']) end it 'is able to parse YAML data with a mixed structure' do is_expected.to run.with_params("---\na: '1'\nb: 2\nc:\n d:\n - :a\n - true\n - false\n") .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [:a, true, false] }) end it 'is able to parse YAML data with a UTF8 and double byte characters' do is_expected.to run.with_params("---\na: ×\nこれ: 記号\nです:\n ©:\n - Á\n - ß\n") .and_return('a' => '×', 'これ' => '記号', 'です' => { '©' => ['Á', 'ß'] }) end it 'does not return the default value if the data was parsed correctly' do is_expected.to run.with_params("---\na: '1'\n", 'default_value') .and_return('a' => '1') end end it 'raises an error with invalid YAML and no default' do is_expected.to run.with_params('["one"') .and_raise_error(Psych::SyntaxError) end context 'with incorrect YAML data' do it 'supports a structure for a default value' do is_expected.to run.with_params('', 'a' => '1') .and_return('a' => '1') end [1, 1.2, nil, true, false, [], {}, :yaml].each do |value| - it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do + it "returns the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end context 'when running on modern rubies' do ['---', '...', '*8', ''].each do |value| - it "should return the default value for an incorrect #{value.inspect} string parameter" do + it "returns the default value for an incorrect #{value.inspect} string parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end end end end diff --git a/spec/functions/private_spec.rb b/spec/functions/private_spec.rb index 7f345f8..e0f2667 100644 --- a/spec/functions/private_spec.rb +++ b/spec/functions/private_spec.rb @@ -1,54 +1,54 @@ # frozen_string_literal: true require 'spec_helper' describe 'private' do it 'issues a warning' do expect(scope).to receive(:warning).with("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Layout/LineLength : unable to cut line to required length begin subject.execute - rescue # rubocop:disable Lint/HandleExceptions + rescue # ignore this end end context 'when called from inside module' do it 'does not fail' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('foo') expect { subject.execute }.not_to raise_error end end context 'with an explicit failure message' do it 'prints the failure message on error' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect { subject.execute('failure message!') }.to raise_error(Puppet::ParseError, %r{failure message!}) end end context 'when called from private class' do it 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('hostclass') expect { subject.execute }.to raise_error(Puppet::ParseError, %r{Class foo::baz is private}) end end context 'when called from private definition' do it 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('definition') expect { subject.execute }.to raise_error(Puppet::ParseError, %r{Definition foo::baz is private}) end end end diff --git a/spec/functions/range_spec.rb b/spec/functions/range_spec.rb index 90728a8..f6d9a2f 100644 --- a/spec/functions/range_spec.rb +++ b/spec/functions/range_spec.rb @@ -1,159 +1,159 @@ # frozen_string_literal: true require 'spec_helper' describe 'range' do it { is_expected.not_to eq(nil) } - describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do + describe 'signature validation in puppet3', unless: RSpec.configuration.puppet_future do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the third.') is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('1..2..3').and_raise_error(Puppet::ParseError, %r{Unable to compute range}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Unknown range format}i) } end - describe 'signature validation in puppet4', :if => RSpec.configuration.puppet_future do + describe 'signature validation in puppet4', if: RSpec.configuration.puppet_future do it { pending 'the puppet 4 implementation' is_expected.to run.with_params.and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params('').and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params({}).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params([]).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(true).and_raise_error(ArgumentError) } it { is_expected.to run.with_params(1, 2, 'foo').and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, []).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, {}).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, true).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params('1..2..3').and_raise_error(ArgumentError) } end context 'with characters as bounds' do it { is_expected.to run.with_params('d', 'a').and_return([]) } it { is_expected.to run.with_params('a', 'a').and_return(['a']) } it { is_expected.to run.with_params('a', 'b').and_return(['a', 'b']) } it { is_expected.to run.with_params('a', 'd').and_return(['a', 'b', 'c', 'd']) } it { is_expected.to run.with_params('a', 'd', 1).and_return(['a', 'b', 'c', 'd']) } it { is_expected.to run.with_params('a', 'd', '1').and_return(['a', 'b', 'c', 'd']) } it { is_expected.to run.with_params('a', 'd', 2).and_return(['a', 'c']) } it { is_expected.to run.with_params('a', 'd', -2).and_return(['a', 'c']) } it { is_expected.to run.with_params('a', 'd', 3).and_return(['a', 'd']) } it { is_expected.to run.with_params('a', 'd', 4).and_return(['a']) } end context 'with strings as bounds' do it { is_expected.to run.with_params('onea', 'oned').and_return(['onea', 'oneb', 'onec', 'oned']) } it { is_expected.to run.with_params('two', 'one').and_return([]) } it { is_expected.to run.with_params('true', 'false').and_return([]) } it { is_expected.to run.with_params('false', 'true').and_return(['false']) } end context 'with integers as bounds' do it { is_expected.to run.with_params(4, 1).and_return([]) } it { is_expected.to run.with_params(1, 1).and_return([1]) } it { is_expected.to run.with_params(1, 2).and_return([1, 2]) } it { is_expected.to run.with_params(1, 4).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, -2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, 3).and_return([1, 4]) } it { is_expected.to run.with_params(1, 4, 4).and_return([1]) } end context 'with integers as strings as bounds' do it { is_expected.to run.with_params('4', '1').and_return([]) } it { is_expected.to run.with_params('1', '1').and_return([1]) } it { is_expected.to run.with_params('1', '2').and_return([1, 2]) } it { is_expected.to run.with_params('1', '4').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', -2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', 3).and_return([1, 4]) } it { is_expected.to run.with_params('1', '4', 4).and_return([1]) } end context 'with prefixed numbers as strings as bounds' do it { is_expected.to run.with_params('host01', 'host04').and_return(['host01', 'host02', 'host03', 'host04']) } it { is_expected.to run.with_params('01', '04').and_return([1, 2, 3, 4]) } end context 'with prefixed numbers as utf8 strings as bounds' do it { is_expected.to run.with_params('ħөŝŧ01', 'ħөŝŧ04').and_return(['ħөŝŧ01', 'ħөŝŧ02', 'ħөŝŧ03', 'ħөŝŧ04']) } end context 'with prefixed numbers as double byte character strings as bounds' do it { is_expected.to run.with_params('ホスト01', 'ホスト04').and_return(['ホスト01', 'ホスト02', 'ホスト03', 'ホスト04']) } end context 'with dash-range syntax' do it { is_expected.to run.with_params('4-1').and_return([]) } it { is_expected.to run.with_params('1-1').and_return([1]) } it { is_expected.to run.with_params('1-2').and_return([1, 2]) } it { is_expected.to run.with_params('1-4').and_return([1, 2, 3, 4]) } end context 'with two-dot-range syntax' do it { is_expected.to run.with_params('4..1').and_return([]) } it { is_expected.to run.with_params('1..1').and_return([1]) } it { is_expected.to run.with_params('1..2').and_return([1, 2]) } it { is_expected.to run.with_params('1..4').and_return([1, 2, 3, 4]) } end context 'with three-dot-range syntax' do it { is_expected.to run.with_params('4...1').and_return([]) } it { is_expected.to run.with_params('1...1').and_return([]) } it { is_expected.to run.with_params('1...2').and_return([1]) } it { is_expected.to run.with_params('1...3').and_return([1, 2]) } it { is_expected.to run.with_params('1...5').and_return([1, 2, 3, 4]) } end describe 'when passing mixed arguments as bounds' do it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Layout/LineLength : unable to cut line to required length is_expected.to run.with_params('0', 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Layout/LineLength : unable to cut line to required length is_expected.to run.with_params(0, 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Layout/LineLength : unable to cut line to required length is_expected.to run.with_params('h0', 'ha').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } end end diff --git a/spec/functions/round_spec.rb b/spec/functions/round_spec.rb index c84d690..7b3baf1 100644 --- a/spec/functions/round_spec.rb +++ b/spec/functions/round_spec.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true require 'spec_helper' -describe 'round', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'round', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params(34.3).and_return(34) } it { is_expected.to run.with_params(-34.3).and_return(-34) } it { is_expected.to run.with_params(34.5).and_return(35) } it { is_expected.to run.with_params(-34.5).and_return(-35) } it { is_expected.to run.with_params(34.7).and_return(35) } it { is_expected.to run.with_params(-34.7).and_return(-35) } it { is_expected.to run.with_params('test').and_raise_error Puppet::ParseError } it { is_expected.to run.with_params('test', 'best').and_raise_error Puppet::ParseError } it { is_expected.to run.with_params(3, 4).and_raise_error Puppet::ParseError } end diff --git a/spec/functions/rstrip_spec.rb b/spec/functions/rstrip_spec.rb index 5ef5c8d..251fb66 100644 --- a/spec/functions/rstrip_spec.rb +++ b/spec/functions/rstrip_spec.rb @@ -1,37 +1,37 @@ # frozen_string_literal: true require 'spec_helper' -describe 'rstrip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'rstrip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return(' one') } it { is_expected.to run.with_params(' one').and_return(' one') } it { is_expected.to run.with_params("\tone").and_return("\tone") } it { is_expected.to run.with_params("\t one").and_return("\t one") } it { is_expected.to run.with_params('one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return(' one') } it { is_expected.to run.with_params(' one ').and_return(' one') } it { is_expected.to run.with_params(' ǿňè ').and_return(' ǿňè') } it { is_expected.to run.with_params("\tone ").and_return("\tone") } it { is_expected.to run.with_params("\t one ").and_return("\t one") } it { is_expected.to run.with_params("one\t").and_return('one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params("\tone\t").and_return("\tone") } it { is_expected.to run.with_params("\t one\t").and_return("\t one") } it { is_expected.to run.with_params(' o n e ').and_return(' o n e') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return(' one') } end diff --git a/spec/functions/seeded_rand_spec.rb b/spec/functions/seeded_rand_spec.rb index 8ca7e45..9ee3b86 100644 --- a/spec/functions/seeded_rand_spec.rb +++ b/spec/functions/seeded_rand_spec.rb @@ -1,60 +1,60 @@ # frozen_string_literal: true require 'spec_helper' describe 'seeded_rand' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1.5, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(-10, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('-10', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('string', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params([], '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params({}, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be a string}) } it 'provides a random number strictly less than the given max' do expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i < 3 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end it 'provides a random number greater or equal to zero' do expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i >= 0 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end it "provides the same 'random' value on subsequent calls for the same host" do expect(seeded_rand(10, 'seed')).to eql(seeded_rand(10, 'seed')) end it 'allows seed to control the random value on a single host' do first_random = seeded_rand(1000, 'seed1') second_different_random = seeded_rand(1000, 'seed2') expect(first_random).not_to eql(second_different_random) end it 'does not return different values for different hosts' do - val1 = seeded_rand(1000, 'foo', :host => 'first.host.com') - val2 = seeded_rand(1000, 'foo', :host => 'second.host.com') + val1 = seeded_rand(1000, 'foo', host: 'first.host.com') + val2 = seeded_rand(1000, 'foo', host: 'second.host.com') expect(val1).to eql(val2) end def seeded_rand(max, seed, args = {}) host = args[:host] || '127.0.0.1' # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn', {}).and_return(host) scope.function_seeded_rand([max, seed]) end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(1000, 'ǿňè') } it { is_expected.to run.with_params(1000, '文字列') } end end diff --git a/spec/functions/size_spec.rb b/spec/functions/size_spec.rb index 21b2b40..386f912 100644 --- a/spec/functions/size_spec.rb +++ b/spec/functions/size_spec.rb @@ -1,40 +1,40 @@ # frozen_string_literal: true require 'spec_helper' -describe 'size', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'size', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } it { is_expected.to run.with_params('1').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } it { is_expected.to run.with_params('1.0').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(3) } it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } it { is_expected.to run.with_params('1' => '2').and_return(1) } it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } - context 'when using a class extending String', :unless => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 do + context 'when using a class extending String', unless: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 do it 'calls its size method' do value = AlsoString.new('asdfghjkl') expect(value).to receive(:size).and_return('foo') expect(subject).to run.with_params(value).and_return('foo') end end end diff --git a/spec/functions/sort_spec.rb b/spec/functions/sort_spec.rb index d6f16d1..3387e75 100644 --- a/spec/functions/sort_spec.rb +++ b/spec/functions/sort_spec.rb @@ -1,39 +1,39 @@ # frozen_string_literal: true require 'spec_helper' -describe 'sort', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'sort', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('stricter input checking') is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{requires string or array}) } it { pending('stricter input checking') is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{requires string or array}) } it { pending('stricter input checking') is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{requires string or array}) } end context 'when called with an array' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(['c', 'b', 'a']).and_return(['a', 'b', 'c']) } end context 'when called with a string' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('cbda').and_return('abcd') } end context 'when called with a number' do it { is_expected.to run.with_params('9478').and_return('4789') } end end diff --git a/spec/functions/strip_spec.rb b/spec/functions/strip_spec.rb index 32d98c1..1328baa 100644 --- a/spec/functions/strip_spec.rb +++ b/spec/functions/strip_spec.rb @@ -1,37 +1,37 @@ # frozen_string_literal: true require 'spec_helper' -describe 'strip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'strip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t one").and_return('one') } it { is_expected.to run.with_params('one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return('one') } it { is_expected.to run.with_params("\tone ").and_return('one') } it { is_expected.to run.with_params("\t one ").and_return('one') } it { is_expected.to run.with_params("one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params("\tone \t").and_return('one') } it { is_expected.to run.with_params("\t one \t").and_return('one') } it { is_expected.to run.with_params(' o n e ').and_return('o n e') } it { is_expected.to run.with_params(' ỏŋέ ').and_return('ỏŋέ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one') } end diff --git a/spec/functions/to_yaml_spec.rb b/spec/functions/to_yaml_spec.rb index 3d18e4d..98985c4 100644 --- a/spec/functions/to_yaml_spec.rb +++ b/spec/functions/to_yaml_spec.rb @@ -1,24 +1,24 @@ # frozen_string_literal: true require 'spec_helper' describe 'to_yaml' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params('').and_return("--- ''\n") } it { is_expected.to run.with_params(true).and_return(%r{--- true\n}) } it { is_expected.to run.with_params('one').and_return(%r{--- one\n}) } it { is_expected.to run.with_params([]).and_return("--- []\n") } it { is_expected.to run.with_params(['one']).and_return("---\n- one\n") } it { is_expected.to run.with_params(['one', 'two']).and_return("---\n- one\n- two\n") } it { is_expected.to run.with_params({}).and_return("--- {}\n") } it { is_expected.to run.with_params('key' => 'value').and_return("---\nkey: value\n") } it { is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => ['twoA', 'twoB']) .and_return("---\none:\n oneA: A\n oneB:\n oneB1: '1'\n oneB2: '2'\ntwo:\n- twoA\n- twoB\n") } it { is_expected.to run.with_params('‰').and_return("--- \"‰\"\n") } it { is_expected.to run.with_params('∇').and_return("--- \"∇\"\n") } - it { is_expected.to run.with_params({ 'foo' => { 'bar' => true, 'baz' => false } }, :indentation => 4).and_return("---\nfoo:\n bar: true\n baz: false\n") } + it { is_expected.to run.with_params({ 'foo' => { 'bar' => true, 'baz' => false } }, indentation: 4).and_return("---\nfoo:\n bar: true\n baz: false\n") } end diff --git a/spec/functions/upcase_spec.rb b/spec/functions/upcase_spec.rb index 8822b94..d110ee1 100644 --- a/spec/functions/upcase_spec.rb +++ b/spec/functions/upcase_spec.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true require 'spec_helper' -describe 'upcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'upcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } end describe 'normal string handling' do it { is_expected.to run.with_params('abc').and_return('ABC') } it { is_expected.to run.with_params('Abc').and_return('ABC') } it { is_expected.to run.with_params('ABC').and_return('ABC') } end describe 'handling classes derived from String' do it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('ABC') } end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['One', 'twO']).and_return(['ONE', 'TWO']) } end end diff --git a/spec/functions/validate_cmd_spec.rb b/spec/functions/validate_cmd_spec.rb index a9f017d..7d8a8a1 100644 --- a/spec/functions/validate_cmd_spec.rb +++ b/spec/functions/validate_cmd_spec.rb @@ -1,43 +1,43 @@ # frozen_string_literal: true require 'spec_helper' -describe 'validate_cmd', :unless => Puppet::Util::Platform.windows? do +describe 'validate_cmd', unless: Puppet::Util::Platform.windows? do let(:touch) { File.exist?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' } describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('should implement stricter type checking') is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{content must be a string}) } it { pending('should implement stricter type checking') is_expected.to run.with_params('', [], '').and_raise_error(Puppet::ParseError, %r{checkscript must be a string}) } it { pending('should implement stricter type checking') is_expected.to run.with_params('', '', []).and_raise_error(Puppet::ParseError, %r{custom error message must be a string}) } end context 'when validation fails' do context 'with % placeholder' do it { is_expected.to run .with_params('', "#{touch} % /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \S+ \/no\/such\/file' returned 1:.*(cannot touch|o such file or)}) } it { is_expected.to run.with_params('', "#{touch} % /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end context 'without % placeholder' do it { is_expected.to run .with_params('', "#{touch} /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \/no\/such\/file \S+' returned 1:.*(cannot touch|o such file or)}) } it { is_expected.to run.with_params('', "#{touch} /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end end end diff --git a/spec/functions/validate_integer_spec.rb b/spec/functions/validate_integer_spec.rb index ccbc4d4..6252a6d 100644 --- a/spec/functions/validate_integer_spec.rb +++ b/spec/functions/validate_integer_spec.rb @@ -1,103 +1,103 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_integer' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', 7.0, -7.0, {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params(invalid, 10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params(invalid, 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params([0, 1, 2, invalid, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end - context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do + context 'when running on modern rubies', unless: RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end - context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do + context 'when running on ruby, which munges hashes weirdly', if: RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end context 'with a maximum limit of 10' do describe 'rejects numbers greater than the limit' do it { is_expected.to run.with_params(11, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10, 100], 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do it { is_expected.to run.with_params(10, 10) } it { is_expected.to run.with_params(1, 10) } it { is_expected.to run.with_params(-1, 10) } it { is_expected.to run.with_params('1', 10) } it { is_expected.to run.with_params('-1', 10) } it { is_expected.to run.with_params([1, 2, 3, 4], 10) } it { is_expected.to run.with_params([1, '2', '3', 4], 10) } end end context 'with a minimum limit of -10' do describe 'rejects numbers greater than the upper limit' do it { is_expected.to run.with_params(11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10, 100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'rejects numbers smaller than the lower limit' do it { is_expected.to run.with_params(-11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params([-10, 1, 2, 10, -100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } end describe 'accepts numbers between and including the limits' do it { is_expected.to run.with_params(10, 10, -10) } it { is_expected.to run.with_params(-10, 10, -10) } it { is_expected.to run.with_params(1, 10, -10) } it { is_expected.to run.with_params(-1, 10, -10) } it { is_expected.to run.with_params('1', 10, -10) } it { is_expected.to run.with_params('-1', 10, -10) } it { is_expected.to run.with_params([1, 2, 3, 4], 10, -10) } it { is_expected.to run.with_params([1, '2', '3', 4], 10, -10) } end end it { is_expected.to run.with_params(10, 10, 10) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10) } end end diff --git a/spec/functions/validate_ip_address_spec.rb b/spec/functions/validate_ip_address_spec.rb index 7b3cd9f..ded6df9 100644 --- a/spec/functions/validate_ip_address_spec.rb +++ b/spec/functions/validate_ip_address_spec.rb @@ -1,66 +1,66 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_ip_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('0.0.0.0') } it { is_expected.to run.with_params('8.8.8.8') } it { is_expected.to run.with_params('127.0.0.1') } it { is_expected.to run.with_params('10.10.10.10') } it { is_expected.to run.with_params('194.232.104.150') } it { is_expected.to run.with_params('244.24.24.24') } it { is_expected.to run.with_params('255.255.255.255') } it { is_expected.to run.with_params('1.2.3.4', '5.6.7.8') } it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('1.2.3.4') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('1.2.3.4') end end context 'with netmasks' do it { is_expected.to run.with_params('8.8.8.8/0') } it { is_expected.to run.with_params('8.8.8.8/16') } it { is_expected.to run.with_params('8.8.8.8/32') } it { is_expected.to run.with_params('8.8.8.8/255.255.0.0') } end end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('1.2.3.4', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } end end diff --git a/spec/functions/validate_ipv4_address_spec.rb b/spec/functions/validate_ipv4_address_spec.rb index c1c0d80..bc8ed76 100644 --- a/spec/functions/validate_ipv4_address_spec.rb +++ b/spec/functions/validate_ipv4_address_spec.rb @@ -1,47 +1,47 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_ipv4_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end end SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_raise_error(Puppet::ParseError, %r{is not a valid IPv4}) } end describe 'invalid inputs' do [{}, [], 1, true].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first, invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end describe 'multiple inputs' do it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS[0], SharedData::IPV4_PATTERNS[1]) } it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS[0], 'invalid ip').and_raise_error(Puppet::ParseError, %r{is not a valid IPv4}) } end end diff --git a/spec/functions/validate_ipv6_address_spec.rb b/spec/functions/validate_ipv6_address_spec.rb index 7db0331..3e1563e 100644 --- a/spec/functions/validate_ipv6_address_spec.rb +++ b/spec/functions/validate_ipv6_address_spec.rb @@ -1,61 +1,61 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_ipv6_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('3ffe:0505:0002::') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('3ffe:0505:0002::') end end describe 'valid inputs' do it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } it { is_expected.to run.with_params('fe80:0000:0000:0000:0204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80::204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:0204:61ff:254.157.241.86') } it { is_expected.to run.with_params('::1') } it { is_expected.to run.with_params('fe80::') } it { is_expected.to run.with_params('2001::') } end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:2.3.4').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:257.1.2.3').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:12345678901234567890.1.26').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('affe:beef').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } - context 'unless running on ruby 1.8.7', :if => RUBY_VERSION != '1.8.7' do + context 'unless running on ruby 1.8.7', if: RUBY_VERSION != '1.8.7' do it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end diff --git a/spec/functions/validate_numeric_spec.rb b/spec/functions/validate_numeric_spec.rb index 3f0ea7e..8b593c3 100644 --- a/spec/functions/validate_numeric_spec.rb +++ b/spec/functions/validate_numeric_spec.rb @@ -1,102 +1,102 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_numeric' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } it { is_expected.to run.with_params(invalid, 10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } it { is_expected.to run.with_params(invalid, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end - context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do + context 'when running on modern rubies', unless: RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end - context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do + context 'when running on ruby, which munges hashes weirdly', if: RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end context 'with a maximum limit of 10.0' do describe 'rejects numbers greater than the limit' do it { is_expected.to run.with_params(11, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do it { is_expected.to run.with_params(10.0, 10.0) } it { is_expected.to run.with_params(1, 10.0) } it { is_expected.to run.with_params(-1, 10.0) } it { is_expected.to run.with_params('1', 10.0) } it { is_expected.to run.with_params('-1', 10.0) } it { is_expected.to run.with_params([1, 2, 3, 4], 10.0) } it { is_expected.to run.with_params([1, '2', '3', 4], 10.0) } end end context 'with a minimum limit of -10.0' do describe 'rejects numbers greater than the upper limit' do it { is_expected.to run.with_params(11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'rejects numbers smaller than the lower limit' do it { is_expected.to run.with_params(-11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params([-10.0, 1, 2, 10.0, -100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } end describe 'accepts numbers between and including the limits' do it { is_expected.to run.with_params(10.0, 10.0, -10.0) } it { is_expected.to run.with_params(-10.0, 10.0, -10.0) } it { is_expected.to run.with_params(1, 10.0, -10.0) } it { is_expected.to run.with_params(-1, 10.0, -10.0) } it { is_expected.to run.with_params('1', 10.0, -10.0) } it { is_expected.to run.with_params('-1', 10.0, -10.0) } it { is_expected.to run.with_params([1, 2, 3, 4], 10.0, -10.0) } it { is_expected.to run.with_params([1, '2', '3', 4], 10.0, -10.0) } end end it { is_expected.to run.with_params(10.0, 10.0, 10.0) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10.0) } end end diff --git a/spec/functions/validate_re_spec.rb b/spec/functions/validate_re_spec.rb index 5462ddb..bfa824e 100644 --- a/spec/functions/validate_re_spec.rb +++ b/spec/functions/validate_re_spec.rb @@ -1,58 +1,58 @@ # frozen_string_literal: true require 'spec_helper' describe 'validate_re' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('', '') end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('', '') } it { is_expected.to run.with_params('', ['']) } it { is_expected.to run.with_params('', [''], 'custom error') } it { is_expected.to run.with_params('one', '^one') } it { is_expected.to run.with_params('one', ['^one', '^two']) } it { is_expected.to run.with_params('one', ['^one', '^two'], 'custom error') } end describe 'invalid inputs' do it { is_expected.to run.with_params('', []).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', ['two']).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', ['two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } it { is_expected.to run.with_params('notone', '^one').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('notone', ['^one', '^two']).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('notone', ['^one', '^two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end describe 'non-string inputs' do [ 1, # Fixnum 3.14, # Float nil, # NilClass true, # TrueClass false, # FalseClass ['10'], # Array :key, # Symbol - { :key => 'val' }, # Hash + { key: 'val' }, # Hash ].each do |input| it { is_expected.to run.with_params(input, '.*').and_raise_error(Puppet::ParseError, %r{needs to be a String}) } end end end end diff --git a/spec/functions/values_spec.rb b/spec/functions/values_spec.rb index 8037a22..b2c3e4b 100644 --- a/spec/functions/values_spec.rb +++ b/spec/functions/values_spec.rb @@ -1,26 +1,26 @@ # frozen_string_literal: true require 'spec_helper' -describe 'values', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'values', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params({}, 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params({}).and_return([]) } it { is_expected.to run.with_params('key' => 'value').and_return(['value']) } it 'returns the array of values' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2', 'duplicate_value_key' => 'value2' }]) expect(result).to match_array(['value1', 'value2', 'value2']) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'かぎ' => '使用', 'ҝĕұ' => '√ẩŀứệ', 'ҝĕұďŭрļǐçằťè' => '√ẩŀứệ' }]) expect(result).to match_array(['使用', '√ẩŀứệ', '√ẩŀứệ']) end end diff --git a/spec/unit/facter/package_provider_spec.rb b/spec/unit/facter/package_provider_spec.rb index bb3c2be..3e75c28 100644 --- a/spec/unit/facter/package_provider_spec.rb +++ b/spec/unit/facter/package_provider_spec.rb @@ -1,45 +1,45 @@ # frozen_string_literal: true require 'spec_helper' require 'puppet/type' require 'puppet/type/package' -describe 'package_provider', :type => :fact do +describe 'package_provider', type: :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } ['4.2.2', '3.7.1 (Puppet Enterprise 3.2.1)'].each do |puppetversion| describe "on puppet ''#{puppetversion}''" do before :each do allow(Facter).to receive(:value).and_return(puppetversion) end context 'when darwin' do it 'returns pkgdmg' do provider = Puppet::Type.type(:package).provider(:pkgdmg) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('pkgdmg') end end context 'when centos 7' do it 'returns yum' do provider = Puppet::Type.type(:package).provider(:yum) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('yum') end end context 'when ubuntu' do it 'returns apt' do provider = Puppet::Type.type(:package).provider(:apt) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('apt') end end end end end diff --git a/spec/unit/facter/pe_version_spec.rb b/spec/unit/facter/pe_version_spec.rb index d921284..e152548 100644 --- a/spec/unit/facter/pe_version_spec.rb +++ b/spec/unit/facter/pe_version_spec.rb @@ -1,81 +1,81 @@ # frozen_string_literal: true require 'spec_helper' describe 'PE Version specs' do # we mock calls for the puppetversion fact, it is not normal to expect nil responses when mocking. RSpec::Mocks.configuration.allow_message_expectations_on_nil = true context 'when puppetversion is nil' do before :each do allow(Facter.fact(:puppetversion)).to receive(:value).and_return(nil) end it 'puppetversion is nil' do expect(Facter.fact(:puppetversion).value).to be_nil end it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end end context 'when PE is installed' do ['2.6.1', '2.10.300'].each do |version| puppetversion = "2.7.19 (Puppet Enterprise #{version})" context "puppetversion => #{puppetversion}" do before :each do allow(Facter).to receive(:value).with(anything).and_call_original allow(Facter).to receive(:value).with('puppetversion').and_return(puppetversion) end (major, minor, patch) = version.split('.') it 'returns true' do expect(Facter.fact(:is_pe).value).to eq(true) end - it "Should have a version of #{version}" do + it "has a version of #{version}" do expect(Facter.fact(:pe_version).value).to eq(version) end - it "Should have a major version of #{major}" do + it "has a major version of #{major}" do expect(Facter.fact(:pe_major_version).value).to eq(major) end - it "Should have a minor version of #{minor}" do + it "has a minor version of #{minor}" do expect(Facter.fact(:pe_minor_version).value).to eq(minor) end - it "Should have a patch version of #{patch}" do + it "has a patch version of #{patch}" do expect(Facter.fact(:pe_patch_version).value).to eq(patch) end end end end context 'when PE is not installed' do before :each do allow(Facter.fact(:puppetversion)).to receive(:value).and_return('2.7.19') end it 'is_pe is false' do expect(Facter.fact(:is_pe).value).to eq(false) end it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end it 'pe_major_version is nil' do expect(Facter.fact(:pe_major_version).value).to be_nil end it 'pe_minor_version is nil' do expect(Facter.fact(:pe_minor_version).value).to be_nil end it 'has a patch version' do expect(Facter.fact(:pe_patch_version).value).to be_nil end end end diff --git a/spec/unit/facter/root_home_spec.rb b/spec/unit/facter/root_home_spec.rb index 6c39887..5421f3e 100644 --- a/spec/unit/facter/root_home_spec.rb +++ b/spec/unit/facter/root_home_spec.rb @@ -1,67 +1,67 @@ # frozen_string_literal: true require 'spec_helper' require 'facter/root_home' describe 'Root Home Specs' do describe Facter::Util::RootHome do context 'when solaris' do let(:root_ent) { 'root:x:0:0:Super-User:/:/sbin/sh' } let(:expected_root_home) { '/' } it 'returns /' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when linux' do let(:root_ent) { 'root:x:0:0:root:/root:/bin/bash' } let(:expected_root_home) { '/root' } it 'returns /root' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when windows' do it 'is nil on windows' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(nil) expect(described_class.returnt_root_home).to be_nil end end end - describe 'root_home', :type => :fact do + describe 'root_home', type: :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do before(:each) do allow(Facter.fact(:kernel)).to receive(:value).and_return('Darwin') allow(Facter.fact(:osfamily)).to receive(:value).and_return('Darwin') end let(:expected_root_home) { '/var/root' } sample_dscacheutil = File.read(fixtures('dscacheutil', 'root')) it 'returns /var/root' do allow(Facter::Util::Resolution).to receive(:exec).with('dscacheutil -q user -a name root').and_return(sample_dscacheutil) expect(Facter.fact(:root_home).value).to eq(expected_root_home) end end context 'when aix' do before(:each) do allow(Facter.fact(:kernel)).to receive(:value).and_return('AIX') allow(Facter.fact(:osfamily)).to receive(:value).and_return('AIX') end let(:expected_root_home) { '/root' } sample_lsuser = File.read(fixtures('lsuser', 'root')) it 'returns /root' do allow(Facter::Util::Resolution).to receive(:exec).with('lsuser -c -a home root').and_return(sample_lsuser) expect(Facter.fact(:root_home).value).to eq(expected_root_home) end end end end diff --git a/spec/unit/facter/service_provider_spec.rb b/spec/unit/facter/service_provider_spec.rb index 8bdd922..4d7d4e1 100644 --- a/spec/unit/facter/service_provider_spec.rb +++ b/spec/unit/facter/service_provider_spec.rb @@ -1,37 +1,37 @@ # frozen_string_literal: true require 'spec_helper' require 'puppet/type' require 'puppet/type/service' -describe 'service_provider', :type => :fact do +describe 'service_provider', type: :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do it 'returns launchd' do provider = Puppet::Type.type(:service).provider(:launchd) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:service_provider).value).to eq('launchd') end end context 'when systemd' do it 'returns systemd' do provider = Puppet::Type.type(:service).provider(:systemd) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:service_provider).value).to eq('systemd') end end context 'when redhat' do it 'returns redhat' do provider = Puppet::Type.type(:service).provider(:redhat) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:service_provider).value).to eq('redhat') end end end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec.rb b/spec/unit/puppet/provider/file_line/ruby_spec.rb index 87fbe43..506160b 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec.rb @@ -1,260 +1,260 @@ # frozen_string_literal: true require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass -describe provider_class, :unless => Puppet::Util::Platform.windows? do +describe provider_class, unless: Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ - :name => 'foo', - :path => tmpfile, - :line => 'foo', + name: 'foo', + path: tmpfile, + line: 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe 'line parameter' do context 'when line exists' do let(:content) { 'foo' } it 'detects the line' do expect(provider).to be_exists end end context 'when line does not exist' do let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end it 'appends the line' do provider.create expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end end end describe 'match parameter' do - let(:params) { { :match => '^bar' } } + let(:params) { { match: '^bar' } } describe 'does not match line - line does not exist - replacing' do let(:content) { "foo bar\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end end describe 'does not match line - line does not exist - appending' do - let(:params) { super().merge(:replace => false) } + let(:params) { super().merge(replace: false) } let(:content) { "foo bar\nbar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when does not match line - line exists' do let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line exists' do - let(:params) { { :match => '^foo' } } + let(:params) { { match: '^foo' } } let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line does not exist' do - let(:params) { { :match => '^foo' } } + let(:params) { { match: '^foo' } } let(:content) { "foo bar\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("foo\nbar") end end end describe 'append_on_no_match' do let(:params) do { - :append_on_no_match => false, - :match => '^foo1$', + append_on_no_match: false, + match: '^foo1$', } end context 'when matching' do let(:content) { "foo1\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nbar") end end context 'when not matching' do let(:content) { "foo3\nbar" } it 'does not affect the file' do expect(provider).to be_exists end end end describe 'replace_all_matches_not_matching_line' do context 'when replace is false' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :replace => false, + replace_all_matches_not_matching_line: true, + replace: false, } end it 'raises an error' do expect { provider.exists? }.to raise_error(Puppet::Error, %r{replace must be true}) end end context 'when match matches line - when there are more matches than lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^foo', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } end let(:content) { "foo\nfoo bar\nbar\nfoo baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nbar\nfoo") end end context 'when match matches line - when there are the same matches and lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^foo', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } end let(:content) { "foo\nfoo\nbar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when match does not match line - when there are more matches than lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo bar\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo bar\nfoo\nfoo") end end context 'when match does not match line - when there are the same matches and lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nfoo\nfoo") end end end context 'when match does not match line - when there are no matches' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo bar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when match does not match line - when there are no matches or lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end it 'appends the line' do provider.create expect(File.read(tmpfile).chomp).to eql("foo bar\nfoo") end end end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb b/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb index 6db4383..f6f7e93 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb @@ -1,376 +1,376 @@ # frozen_string_literal: true require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass -describe provider_class, :unless => Puppet::Util::Platform.windows? do +describe provider_class, unless: Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ - :name => 'foo', - :path => tmpfile, - :line => 'foo', + name: 'foo', + path: tmpfile, + line: 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe '#create' do context 'when adding' do pending('To be added.') end context 'when replacing' do let :params do { - :line => 'foo = bar', - :match => '^foo\s*=.*$', - :replace => false, + line: 'foo = bar', + match: '^foo\s*=.*$', + replace: false, } end let(:content) { "foo1\nfoo=blah\nfoo2\nfoo3" } it "providor 'be_exists'" do expect(provider).to be_exists end it 'does not replace the matching line' do provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo=blah\nfoo2\nfoo3") end it 'appends the line if no matches are found' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } expect(provider.exists?).to be false provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar") end it 'raises an error with invalid values' do expect { @resource = Puppet::Type::File_line.new( - :name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :replace => 'asgadga', + name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', replace: 'asgadga', ) }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) end end end describe '#destroy' do pending('To be added?') end context 'when matching' do # rubocop:disable RSpec/InstanceVariable : replacing before with let breaks the tests, variables need to be altered within it block : multi before :each do @resource = Puppet::Type::File_line.new( - :name => 'foo', - :path => tmpfile, - :line => 'foo = bar', - :match => '^foo\s*=.*$', + name: 'foo', + path: tmpfile, + line: 'foo = bar', + match: '^foo\s*=.*$', ) @provider = provider_class.new(@resource) end describe 'using match' do it 'raises an error if more than one line matches, and should not have modified the file' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } expect { @provider.create }.to raise_error(Puppet::Error, %r{More than one line.*matches}) expect(File.read(tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz") end it 'replaces all lines that matches' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :multiple => true) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar") end it 'replaces all lines that match, even when some lines are correct' do - @resource = Puppet::Type::File_line.new(:name => 'neil', :path => tmpfile, :line => "\thard\tcore\t0\n", :match => '^[ \t]hard[ \t]+core[ \t]+.*', :multiple => true) + @resource = Puppet::Type::File_line.new(name: 'neil', path: tmpfile, line: "\thard\tcore\t0\n", match: '^[ \t]hard[ \t]+core[ \t]+.*', multiple: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") } @provider.create expect(File.read(tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0") end it 'raises an error with invalid values' do expect { @resource = Puppet::Type::File_line.new( - :name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :multiple => 'asgadga', + name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: 'asgadga', ) }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) end it 'replaces a line that matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end it 'adds a new line if no lines match' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } @provider.create expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n") end it 'does nothing if the exact line already exists' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = bar\nfoo2") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end end describe 'using match+append_on_no_match - when there is a match' do it 'replaces line' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :match => '^foo3$', :append_on_no_match => false) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") end end describe 'using match+append_on_no_match - when there is no match' do it 'does not add line after no matches found' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :match => '^foo3$', :append_on_no_match => false) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") end end end context 'when match+replace+append_on_no_match' do pending('to do') end context 'when after' do let :resource do Puppet::Type::File_line.new( - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :after => '^foo1', + name: 'foo', + path: tmpfile, + line: 'inserted = line', + after: '^foo1', ) end let :provider do provider_class.new(resource) end context 'when match and after set' do shared_context 'when resource_create' do let(:match) { '^foo2$' } let(:after) { '^foo1$' } let(:resource) do Puppet::Type::File_line.new( - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :after => after, - :match => match, + name: 'foo', + path: tmpfile, + line: 'inserted = line', + after: after, + match: match, ) end end before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nfoo = baz") } end describe 'inserts at match' do include_context 'resource_create' it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz") } end describe 'inserts a new line after when no match' do include_context 'resource_create' do let(:match) { '^nevergoingtomatch$' } end it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz") } end describe 'append to end of file if no match for both after and match' do include_context 'resource_create' do let(:match) { '^nevergoingtomatch$' } let(:after) { '^stillneverafter' } end it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line") } end end context 'with one line matching the after expression' do before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } end it 'inserts the specified line after the line matching the "after" expression' do provider.create expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz") end end context 'with multiple lines matching the after expression' do before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") } end it 'errors out stating "One or no line must match the pattern"' do expect { provider.create }.to raise_error(Puppet::Error, %r{One or no line must match the pattern}) end it 'adds the line after all lines matching the after expression' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :after => '^foo1$', :multiple => true) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', after: '^foo1$', multiple: true) @provider = provider_class.new(@resource) @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz") end end context 'with no lines matching the after expression' do let :content do "foo3\nfoo = blah\nfoo2\nfoo = baz\n" end before :each do File.open(tmpfile, 'w') { |fh| fh.write(content) } end it 'appends the specified line to the file' do provider.create expect(File.read(tmpfile)).to eq(content << resource[:line] << "\n") end end end context 'when removing with a line' do before :each do # TODO: these should be ported over to use the PuppetLabs spec_helper # file fixtures once the following pull request has been merged: # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files @resource = Puppet::Type::File_line.new( - :name => 'foo', - :path => tmpfile, - :line => 'foo', - :ensure => 'absent', + name: 'foo', + path: tmpfile, + line: 'foo', + ensure: 'absent', ) @provider = provider_class.new(@resource) end it 'removes the line if it exists' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'removes the line without touching the last new line' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'removes any occurence of the line' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'example in the docs' do - @resource = Puppet::Type::File_line.new(:name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128') + @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128') @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end end context 'when removing with a match' do before :each do @resource = Puppet::Type::File_line.new( - :name => 'foo', - :path => tmpfile, - :line => 'foo2', - :ensure => 'absent', - :match => 'o$', - :match_for_absence => true, + name: 'foo', + path: tmpfile, + line: 'foo2', + ensure: 'absent', + match: 'o$', + match_for_absence: true, ) @provider = provider_class.new(@resource) end it 'finds a line to match' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } expect(@provider.exists?).to be true end it 'removes one line if it matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'the line parameter is actually not used at all but is silently ignored if here' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'supercalifragilisticexpialidocious', :ensure => 'absent', :match => 'o$', :match_for_absence => true) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'supercalifragilisticexpialidocious', ensure: 'absent', match: 'o$', match_for_absence: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'and may not be here and does not need to be here' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :ensure => 'absent', :match => 'o$', :match_for_absence => true) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, ensure: 'absent', match: 'o$', match_for_absence: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'raises an error if more than one line matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } expect { @provider.destroy }.to raise_error(Puppet::Error, %r{More than one line}) end it 'removes multiple lines if :multiple is true' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$', :multiple => true, :match_for_absence => true) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', multiple: true, match_for_absence: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'ignores the match if match_for_absence is not specified' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$') + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$') @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo\n") end it 'ignores the match if match_for_absence is false' do - @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$', :match_for_absence => false) + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', match_for_absence: false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo\n") end it 'example in the docs' do @resource = Puppet::Type::File_line.new( - :name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', - :match => '^export\ HTTP_PROXY\=', :match_for_absence => true + name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + match: '^export\ HTTP_PROXY\=', match_for_absence: true ) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end it 'example in the docs showing line is redundant' do - @resource = Puppet::Type::File_line.new(:name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :match => '^export\ HTTP_PROXY\=', :match_for_absence => true) + @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, match: '^export\ HTTP_PROXY\=', match_for_absence: true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end end end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb b/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb index 74cb4d9..456ddd6 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb @@ -1,137 +1,137 @@ # frozen_string_literal: true require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass -describe provider_class, :unless => Puppet::Util::Platform.windows? do +describe provider_class, unless: Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ - :name => 'foo', - :path => tmpfile, - :line => 'foo', + name: 'foo', + path: tmpfile, + line: 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe 'customer use cases - no lines' do describe 'MODULES-5003' do let(:params) do { - :line => "*\thard\tcore\t0", - :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", - :multiple => true, + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, } end let(:content) { "* hard core 90\n* hard core 10\n" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") end end describe 'MODULES-5003 - one match, one line - just ensure the line exists' do let(:params) do { - :line => "*\thard\tcore\t0", - :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", - :multiple => true, + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, } end let(:content) { "* hard core 90\n* hard core 0\n" } it 'does not request changes' do expect(provider).to be_exists end end describe 'MODULES-5003 - one match, one line - replace all matches, even when line exists' do let(:params) do { - :line => "*\thard\tcore\t0", - :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", - :multiple => true, + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, - }.merge(:replace_all_matches_not_matching_line => true) + }.merge(replace_all_matches_not_matching_line: true) end let(:content) { "* hard core 90\n* hard core 0\n" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") end end describe 'MODULES-5651 - match, no line' do let(:params) do { - :line => 'LogLevel=notice', - :match => '^#LogLevel$', + line: 'LogLevel=notice', + match: '^#LogLevel$', } end let(:content) { "#LogLevel\nstuff" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("LogLevel=notice\nstuff") end end describe 'MODULES-5651 - match, line' do let(:params) do { - :line => 'LogLevel=notice', - :match => '^#LogLevel$', + line: 'LogLevel=notice', + match: '^#LogLevel$', } end let(:content) { "#Loglevel\nLogLevel=notice\nstuff" } it 'does not request changes' do expect(provider).to be_exists end end describe 'MODULES-5651 - no match, line' do let(:params) do { - :line => 'LogLevel=notice', - :match => '^#LogLevel$', + line: 'LogLevel=notice', + match: '^#LogLevel$', } end let(:content) { "LogLevel=notice\nstuff" } it 'does not request changes' do expect(provider).to be_exists end end end end diff --git a/spec/unit/puppet/type/anchor_spec.rb b/spec/unit/puppet/type/anchor_spec.rb index c6f6615..9dc4ebd 100644 --- a/spec/unit/puppet/type/anchor_spec.rb +++ b/spec/unit/puppet/type/anchor_spec.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true require 'spec_helper' -anchor = Puppet::Type.type(:anchor).new(:name => 'ntp::begin') +anchor = Puppet::Type.type(:anchor).new(name: 'ntp::begin') describe anchor do it 'stringifies normally' do expect(anchor.to_s).to eq('Anchor[ntp::begin]') end end diff --git a/spec/unit/puppet/type/file_line_spec.rb b/spec/unit/puppet/type/file_line_spec.rb index 5fa6136..e506b13 100644 --- a/spec/unit/puppet/type/file_line_spec.rb +++ b/spec/unit/puppet/type/file_line_spec.rb @@ -1,113 +1,113 @@ # frozen_string_literal: true require 'spec_helper' require 'tempfile' describe Puppet::Type.type(:file_line) do let :tmp_path do if Puppet::Util::Platform.windows? 'C:\tmp\path' else '/tmp/path' end end let :my_path do if Puppet::Util::Platform.windows? 'C:\my\path' else '/my/path' end end let :file_line do - Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => tmp_path) + Puppet::Type.type(:file_line).new(name: 'foo', line: 'line', path: tmp_path) end it 'accepts a line' do file_line[:line] = 'my_line' expect(file_line[:line]).to eq('my_line') end it 'accepts a path' do file_line[:path] = my_path expect(file_line[:path]).to eq(my_path) end it 'accepts a match regex' do file_line[:match] = '^foo.*$' expect(file_line[:match]).to eq('^foo.*$') end it 'accepts a match regex that does not match the specified line' do expect { Puppet::Type.type(:file_line).new( - :name => 'foo', :path => my_path, :line => 'foo=bar', :match => '^bar=blah$', + name: 'foo', path: my_path, line: 'foo=bar', match: '^bar=blah$', ) }.not_to raise_error end it 'accepts a match regex that does match the specified line' do expect { Puppet::Type.type(:file_line).new( - :name => 'foo', :path => my_path, :line => 'foo=bar', :match => '^\s*foo=.*$', + name: 'foo', path: my_path, line: 'foo=bar', match: '^\s*foo=.*$', ) }.not_to raise_error end it 'accepts utf8 characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'ƒồỗ', :path => my_path, :line => 'ƒồỗ=ьåя', :match => '^ьåя=βļάħ$', + name: 'ƒồỗ', path: my_path, line: 'ƒồỗ=ьåя', match: '^ьåя=βļάħ$', ) }.not_to raise_error end it 'accepts double byte characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'フーバー', :path => my_path, :line => 'この=それ', :match => '^この=ああ$', + name: 'フーバー', path: my_path, line: 'この=それ', match: '^この=ああ$', ) }.not_to raise_error end it 'accepts posix filenames' do file_line[:path] = tmp_path expect(file_line[:path]).to eq(tmp_path) end it 'does not accept unqualified path' do expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, %r{File paths must be fully qualified}) end it 'requires that a line is specified' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path) }.to raise_error(Puppet::Error, %r{line is a required attribute}) + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path) }.to raise_error(Puppet::Error, %r{line is a required attribute}) end it 'does not require that a line is specified when matching for absence' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error # rubocop:disable Layout/LineLength + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, ensure: :absent, match_for_absence: :true, match: 'match') }.not_to raise_error end it 'although if a line is specified anyway when matching for absence it still works and the line is silently ignored' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :line => 'i_am_irrelevant', :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error # rubocop:disable Layout/LineLength + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, line: 'i_am_irrelevant', ensure: :absent, match_for_absence: :true, match: 'match') }.not_to raise_error end it 'requires that a file is specified' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, %r{path is a required attribute}) + expect { Puppet::Type.type(:file_line).new(name: 'foo', line: 'path') }.to raise_error(Puppet::Error, %r{path is a required attribute}) end it 'defaults to ensure => present' do expect(file_line[:ensure]).to eq :present end it 'defaults to replace => true' do expect(file_line[:replace]).to eq :true end it 'defaults to encoding => UTF-8' do expect(file_line[:encoding]).to eq 'UTF-8' end it 'accepts encoding => iso-8859-1' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :present, :encoding => 'iso-8859-1', :line => 'bar') }.not_to raise_error + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, ensure: :present, encoding: 'iso-8859-1', line: 'bar') }.not_to raise_error end it 'autorequires the file it manages' do catalog = Puppet::Resource::Catalog.new - file = Puppet::Type.type(:file).new(:name => tmp_path) + file = Puppet::Type.type(:file).new(name: tmp_path) catalog.add_resource file catalog.add_resource file_line relationship = file_line.autorequire.find do |rel| (rel.source.to_s == "File[#{tmp_path}]") && (rel.target.to_s == file_line.to_s) end expect(relationship).to be_a Puppet::Relationship end it 'does not autorequire the file it manages if it is not managed' do catalog = Puppet::Resource::Catalog.new catalog.add_resource file_line expect(file_line.autorequire).to be_empty end end