diff --git a/lib/puppet/functions/parsehocon.rb b/lib/puppet/functions/parsehocon.rb new file mode 100644 index 0000000..6b7ae62 --- /dev/null +++ b/lib/puppet/functions/parsehocon.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +# @summary +# This function accepts HOCON as a string and converts it into the correct +# Puppet structure +# +# @return +# Data +# +# @example How to parse hocon +# $data = parsehocon("{any valid hocon: string}") +# +Puppet::Functions.create_function(:parsehocon) do + # @param hocon_string A valid HOCON string + # @param default An optional default to return if parsing hocon_string fails + dispatch :parsehocon do + param 'String', :hocon_string + optional_param 'Any', :default + end + + def parsehocon(hocon_string, default = :no_default_provided) + require 'hocon/config_factory' + + begin + data = Hocon::ConfigFactory.parse_string(hocon_string) + data.resolve.root.unwrapped + rescue Hocon::ConfigError::ConfigParseError => err + Puppet.debug("Parsing hocon failed with error: #{err.message}") + raise err if default == :no_default_provided + default + end + end +end diff --git a/spec/functions/parsehocon_spec.rb b/spec/functions/parsehocon_spec.rb new file mode 100644 index 0000000..4eae3ab --- /dev/null +++ b/spec/functions/parsehocon_spec.rb @@ -0,0 +1,8 @@ +require 'spec_helper' + +describe 'parsehocon' do + it { is_expected.to run.with_params('').and_return({}) } + it { is_expected.to run.with_params('valid hocon: string').and_return('valid hocon' => 'string') } + it { is_expected.to run.with_params('invalid').and_raise_error(Hocon::ConfigError::ConfigParseError) } + it { is_expected.to run.with_params('invalid', 'default').and_return('default') } +end