Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / loadjson.rb
1 module Puppet::Parser::Functions
2   newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args|
3 Load a JSON file containing an array, string, or hash, and return the data
4 in the corresponding native data type.
5 The second parameter is the default value. It will be returned if the file
6 was not found or could not be parsed.
7
8 For example:
9
10     $myhash = loadjson('/etc/puppet/data/myhash.json')
11     $myhash = loadjson('no-file.json', {'default' => 'value'})
12   ENDHEREDOC
13
14     raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
15
16     if File.exists?(args[0])
17       begin
18         content = File.read(args[0])
19         PSON::load(content) || args[1]
20       rescue Exception => e
21         if args[1]
22           args[1]
23         else
24           raise e
25         end
26       end
27     else
28       warning("Can't load '#{args[0]}' File does not exist!")
29       args[1]
30     end
31
32   end
33
34 end