From eb948c4a0dc36790c5444fc236b0154c3d716c58 Mon Sep 17 00:00:00 2001
From: Dmitry Ilyin <dilyin@mirantis.com>
Date: Mon, 24 Aug 2015 22:00:18 +0300
Subject: [MODULES-2462] Improve parseyaml function

* Add default value support
  Second argument will be returned if yaml cannot be parsed
  instead of false value
* Update tests
---
 lib/puppet/parser/functions/parsejson.rb | 23 ++++++++++++-----------
 lib/puppet/parser/functions/parseyaml.rb | 20 +++++++++++---------
 2 files changed, 23 insertions(+), 20 deletions(-)

(limited to 'lib/puppet/parser')

diff --git a/lib/puppet/parser/functions/parsejson.rb b/lib/puppet/parser/functions/parsejson.rb
index a9a16a4..f822fc4 100644
--- a/lib/puppet/parser/functions/parsejson.rb
+++ b/lib/puppet/parser/functions/parsejson.rb
@@ -3,21 +3,22 @@
 #
 
 module Puppet::Parser::Functions
-  newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS
-This function accepts JSON as a string and converts into the correct Puppet
-structure.
-    EOS
+  newfunction(:parsejson, :type => :rvalue, :arity => -2, :doc => <<-EOS
+This function accepts JSON as a string and converts it into the correct
+Puppet structure.
+
+The optional second argument can be used to pass a default value that will
+be returned if the parsing of YAML string have failed.
+  EOS
   ) do |arguments|
+    raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
 
-    if (arguments.size != 1) then
-      raise(Puppet::ParseError, "parsejson(): Wrong number of arguments "+
-        "given #{arguments.size} for 1")
+    begin
+      PSON::load(arguments[0]) || arguments[1]
+    rescue Exception
+      arguments[1]
     end
 
-    json = arguments[0]
-
-    # PSON is natively available in puppet
-    PSON.load(json)
   end
 end
 
diff --git a/lib/puppet/parser/functions/parseyaml.rb b/lib/puppet/parser/functions/parseyaml.rb
index 53d54fa..d38b3ef 100644
--- a/lib/puppet/parser/functions/parseyaml.rb
+++ b/lib/puppet/parser/functions/parseyaml.rb
@@ -3,20 +3,22 @@
 #
 
 module Puppet::Parser::Functions
-  newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS
+  newfunction(:parseyaml, :type => :rvalue, :arity => -2, :doc => <<-EOS
 This function accepts YAML as a string and converts it into the correct
 Puppet structure.
-    EOS
-  ) do |arguments|
-
-    if (arguments.size != 1) then
-      raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+
-        "given #{arguments.size} for 1")
-    end
 
+The optional second argument can be used to pass a default value that will
+be returned if the parsing of YAML string have failed.
+  EOS
+  ) do |arguments|
+    raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
     require 'yaml'
 
-    YAML::load(arguments[0])
+    begin
+      YAML::load(arguments[0]) || arguments[1]
+    rescue Exception
+      arguments[1]
+    end
 
   end
 end
-- 
cgit v1.2.3