Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / loadjson.rb
1 #
2 # loadjson.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args|
7     @summary
8       Load a JSON file containing an array, string, or hash, and return the data
9       in the corresponding native data type.
10
11     The first parameter can be a file path or a URL.
12     The second parameter is the default value. It will be returned if the file
13     was not found or could not be parsed.
14
15     @return [Array|String|Hash]
16       The data stored in the JSON file, the type depending on the type of data that was stored.
17
18     @example Example Usage:
19       $myhash = loadjson('/etc/puppet/data/myhash.json')
20       $myhash = loadjson('https://example.local/my_hash.json')
21       $myhash = loadjson('https://username:password@example.local/my_hash.json')
22       $myhash = loadjson('no-file.json', {'default' => 'value'})
23   DOC
24
25     raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
26     require 'open-uri'
27     begin
28       if args[0].start_with?('http://', 'https://')
29         username = ''
30         password = ''
31         if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)}))
32           # If URL is in the format of https://username:password@example.local/my_hash.yaml
33           protocol, username, password, path = match.captures
34           url = "#{protocol}#{path}"
35         elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)}))
36           # If URL is in the format of https://username@example.local/my_hash.yaml
37           protocol, username, path = match.captures
38           url = "#{protocol}#{path}"
39         else
40           url = args[0]
41         end
42         begin
43           contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password])
44         rescue OpenURI::HTTPError => err
45           res = err.io
46           warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'")
47           args[1]
48         end
49         PSON.load(contents) || args[1]
50       elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code
51         content = File.read(args[0])
52         PSON.load(content) || args[1]
53       else
54         warning("Can't load '#{args[0]}' File does not exist!")
55         args[1]
56       end
57     rescue StandardError => e
58       raise e unless args[1]
59       args[1]
60     end
61   end
62 end