diff modules/stdlib/lib/puppet/parser/functions/loadjson.rb @ 272:c42fb28cff86

Update to a newer Python module This also pulls in an EPEL module (which we don't use) and a newer stdlib version.
author IBBoard <dev@ibboard.co.uk>
date Fri, 03 Jan 2020 19:56:04 +0000
parents
children d9352a684e62
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/stdlib/lib/puppet/parser/functions/loadjson.rb	Fri Jan 03 19:56:04 2020 +0000
@@ -0,0 +1,32 @@
+#
+# loadjson.rb
+#
+module Puppet::Parser::Functions
+  newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args|
+    Load a JSON file containing an array, string, or hash, and return the data
+    in the corresponding native data type.
+    The second parameter is the default value. It will be returned if the file
+    was not found or could not be parsed.
+
+    For example:
+
+        $myhash = loadjson('/etc/puppet/data/myhash.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
+
+    if File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code
+      begin
+        content = File.read(args[0])
+        PSON.load(content) || args[1]
+      rescue StandardError => e
+        raise e unless args[1]
+        args[1]
+      end
+    else
+      warning("Can't load '#{args[0]}' File does not exist!")
+      args[1]
+    end
+  end
+end