Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Porting functions to the modern Puppet 4.x API #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions lib/puppet/functions/consul/consul_sorted_json.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# This is an autogenerated function, ported from the original legacy version.
# It /should work/ as is, but will not have all the benefits of the modern
# function API. You should see the function docs to learn how to add function
# signatures for type safety and to document this function using puppet-strings.
#
# https://puppet.com/docs/puppet/latest/custom_functions_ruby.html
#
# ---- original file header ----
require 'json'

module JSON
class << self
@@loop = 0

def sorted_generate(obj)
case obj
when NilClass, :undef, Fixnum, Float, TrueClass, FalseClass, String
return simple_generate(obj)
when Array
arrayRet = []
obj.each do |a|
arrayRet.push(sorted_generate(a))
end
return "[" << arrayRet.join(',') << "]";
when Hash
ret = []
obj.keys.sort.each do |k|
ret.push(k.to_json << ":" << sorted_generate(obj[k]))
end
return "{" << ret.join(",") << "}";
else
raise Exception.new("Unable to handle object of type #{obj.class.name} with value #{obj.inspect}")
end
end

def sorted_pretty_generate(obj, indent_len=4)

# Indent length
indent = " " * indent_len

case obj
when NilClass, :undef, Fixnum, Float, TrueClass, FalseClass, String
return simple_generate(obj)
when Array
arrayRet = []

# We need to increase the loop count before #each so the objects inside are indented twice.
# When we come out of #each we decrease the loop count so the closing brace lines up properly.
#
# If you start with @@loop = 1, the count will be as follows
#
# "start_join": [ <-- @@loop == 1
# "192.168.50.20", <-- @@loop == 2
# "192.168.50.21", <-- @@loop == 2
# "192.168.50.22" <-- @@loop == 2
# ] <-- closing brace <-- @@loop == 1
#
@@loop += 1
obj.each do |a|
arrayRet.push(sorted_pretty_generate(a, indent_len))
end
@@loop -= 1

return "[\n#{indent * (@@loop + 1)}" << arrayRet.join(",\n#{indent * (@@loop + 1)}") << "\n#{indent * @@loop}]";

when Hash
ret = []

# This loop works in a similar way to the above
@@loop += 1
obj.keys.sort.each do |k|
ret.push("#{indent * @@loop}" << k.to_json << ": " << sorted_pretty_generate(obj[k], indent_len))
end
@@loop -= 1

return "{\n" << ret.join(",\n") << "\n#{indent * @@loop}}";
else
raise Exception.new("Unable to handle object of type #{obj.class.name} with value #{obj.inspect}")
end

end # end def
private
# simplify jsonification of standard types
def simple_generate(obj)
case obj
when NilClass, :undef
'null'
when Fixnum, Float, TrueClass, FalseClass
"#{obj}"
else
# Should be a string
# keep string integers unquoted
(obj =~ /\A[-]?\d+\z/) ? obj : obj.to_json
end
end

end # end class

end # end module


# ---- original file header ----
#
# @summary
# This function takes unsorted hash and outputs JSON object making sure the keys are sorted.
#Optionally you can pass 2 additional parameters, pretty generate and indent length.
#
#*Examples:*
#
# -------------------
# -- UNSORTED HASH --
# -------------------
# unsorted_hash = {
# 'client_addr' => '127.0.0.1',
# 'bind_addr' => '192.168.34.56',
# 'start_join' => [
# '192.168.34.60',
# '192.168.34.61',
# '192.168.34.62',
# ],
# 'ports' => {
# 'rpc' => 8567,
# 'https' => 8500,
# 'http' => -1,
# },
# }
#
# -----------------
# -- SORTED JSON --
# -----------------
#
# consul_sorted_json(unsorted_hash)
#
# {"bind_addr":"192.168.34.56","client_addr":"127.0.0.1",
# "ports":{"http":-1,"https":8500,"rpc":8567},
# "start_join":["192.168.34.60","192.168.34.61","192.168.34.62"]}
#
# ------------------------
# -- PRETTY SORTED JSON --
# ------------------------
# Params: data <hash>, pretty <true|false>, indent <int>.
#
# consul_sorted_json(unsorted_hash, true, 4)
#
# {
# "bind_addr": "192.168.34.56",
# "client_addr": "127.0.0.1",
# "ports": {
# "http": -1,
# "https": 8500,
# "rpc": 8567
# },
# "start_join": [
# "192.168.34.60",
# "192.168.34.61",
# "192.168.34.62"
# ]
# }
#
#
#
Puppet::Functions.create_function(:'consul::consul_sorted_json') do
# @param args
# The original array of arguments. Port this to individually managed params
# to get the full benefit of the modern function API.
#
# @return [Data type]
# Describe what the function returns here
#
dispatch :default_impl do
# Call the method named 'default_impl' when this is matched
# Port this to match individual params for better type safety
repeated_param 'Any', :args
end


def default_impl(*args)


unsorted_hash = args[0] || {}
pretty = args[1] || false
indent_len = args[2].to_i || 4

if pretty
return JSON.sorted_pretty_generate(unsorted_hash, indent_len) << "\n"
else
return JSON.sorted_generate(unsorted_hash)
end

end
end
82 changes: 82 additions & 0 deletions lib/puppet/functions/consul/consul_validate_checks.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# This is an autogenerated function, ported from the original legacy version.
# It /should work/ as is, but will not have all the benefits of the modern
# function API. You should see the function docs to learn how to add function
# signatures for type safety and to document this function using puppet-strings.
#
# https://puppet.com/docs/puppet/latest/custom_functions_ruby.html
#
# ---- original file header ----
def validate_checks(obj)
case obj
when Array
obj.each do |c|
validate_checks(c)
end
when Hash
if ( (obj.key?("http") || obj.key?("script") || obj.key?("tcp")) && (! obj.key?("interval")) )
raise Puppet::ParseError.new('interval must be defined for tcp, http, and script checks')
end

if obj.key?("ttl")
if (obj.key?("http") || obj.key?("script") || obj.key?("tcp") || obj.key?("interval"))
raise Puppet::ParseError.new('script, http, tcp, and interval must not be defined for ttl checks')
end
elsif obj.key?("http")
if (obj.key?("script") || obj.key?("tcp"))
raise Puppet::ParseError.new('script and tcp must not be defined for http checks')
end
elsif obj.key?("tcp")
if (obj.key?("http") || obj.key?("script"))
raise Puppet::ParseError.new('script and http must not be defined for tcp checks')
end
elsif obj.key?("script")
if (obj.key?("http") || obj.key?("tcp"))
raise Puppet::ParseError.new('http and tcp must not be defined for script checks')
end
else
raise Puppet::ParseError.new('One of ttl, script, tcp, or http must be defined.')
end
else
raise Puppet::ParseError.new("Unable to handle object of type <%s>" % obj.class.to_s)
end
end

# ---- original file header ----
#
# @summary
# This function validates the contents of an array of checks
#
#*Examples:*
#
# consul_validate_checks({'key'=>'value'})
# consul_validate_checks([
# {'key'=>'value'},
# {'key'=>'value'}
# ])
#
#Would return: true if valid, and raise exception otherwise
#
#
Puppet::Functions.create_function(:'consul::consul_validate_checks') do
# @param arguments
# The original array of arguments. Port this to individually managed params
# to get the full benefit of the modern function API.
#
# @return [Data type]
# Describe what the function returns here
#
dispatch :default_impl do
# Call the method named 'default_impl' when this is matched
# Port this to match individual params for better type safety
repeated_param 'Any', :arguments
end


def default_impl(*arguments)

raise(Puppet::ParseError, "validate_checks(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size != 1
return validate_checks(arguments[0])

end
end
41 changes: 41 additions & 0 deletions spec/functions/consul_consul_sorted_json_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require 'spec_helper'

describe 'consul::consul_sorted_json' do
# without knowing details about the implementation, this is the only test
# case that we can autogenerate. You should add more examples below!
it { is_expected.not_to eq(nil) }

#################################
# Below are some example test cases. You may uncomment and modify them to match
# your needs. Notice that they all expect the base error class of `StandardError`.
# This is because the autogenerated function uses an untyped array for parameters
# and relies on your implementation to do the validation. As you convert your
# function to proper dispatches and typed signatures, you should change the
# expected error of the argument validation examples to `ArgumentError`.
#
# Other error types you might encounter include
#
# * StandardError
# * ArgumentError
# * Puppet::ParseError
#
# Read more about writing function unit tests at https://rspec-puppet.com/documentation/functions/
#
# it 'raises an error if called with no argument' do
# is_expected.to run.with_params.and_raise_error(StandardError)
# end
#
# it 'raises an error if there is more than 1 arguments' do
# is_expected.to run.with_params({ 'foo' => 1 }, 'bar' => 2).and_raise_error(StandardError)
# end
#
# it 'raises an error if argument is not the proper type' do
# is_expected.to run.with_params('foo').and_raise_error(StandardError)
# end
#
# it 'returns the proper output' do
# is_expected.to run.with_params(123).and_return('the expected output')
# end
#################################

end
41 changes: 41 additions & 0 deletions spec/functions/consul_consul_validate_checks_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require 'spec_helper'

describe 'consul::consul_validate_checks' do
# without knowing details about the implementation, this is the only test
# case that we can autogenerate. You should add more examples below!
it { is_expected.not_to eq(nil) }

#################################
# Below are some example test cases. You may uncomment and modify them to match
# your needs. Notice that they all expect the base error class of `StandardError`.
# This is because the autogenerated function uses an untyped array for parameters
# and relies on your implementation to do the validation. As you convert your
# function to proper dispatches and typed signatures, you should change the
# expected error of the argument validation examples to `ArgumentError`.
#
# Other error types you might encounter include
#
# * StandardError
# * ArgumentError
# * Puppet::ParseError
#
# Read more about writing function unit tests at https://rspec-puppet.com/documentation/functions/
#
# it 'raises an error if called with no argument' do
# is_expected.to run.with_params.and_raise_error(StandardError)
# end
#
# it 'raises an error if there is more than 1 arguments' do
# is_expected.to run.with_params({ 'foo' => 1 }, 'bar' => 2).and_raise_error(StandardError)
# end
#
# it 'raises an error if argument is not the proper type' do
# is_expected.to run.with_params('foo').and_raise_error(StandardError)
# end
#
# it 'returns the proper output' do
# is_expected.to run.with_params(123).and_return('the expected output')
# end
#################################

end