Add puppet/archive module
[mirror/dsa-puppet.git] / 3rdparty / modules / archive / lib / puppet / functions / archive / artifactory_latest_url.rb
1 require 'json'
2 require 'puppet_x/bodeco/util'
3
4 Puppet::Functions.create_function(:'archive::artifactory_latest_url') do
5   dispatch :artifactory_latest_url do
6     param 'Variant[Stdlib::HTTPUrl, Stdlib::HTTPSUrl]', :url
7     param 'Hash', :maven_data
8   end
9
10   def artifactory_latest_url(url, maven_data)
11     # Turn provided artifactory URL into the fileinfo API endpoint of the parent directory
12     uri = URI(url.sub('/artifactory/', '/artifactory/api/storage/')[%r{^(.*)/.*$}, 1])
13
14     response = PuppetX::Bodeco::Util.content(uri)
15     content  = JSON.parse(response)
16
17     uris = if maven_data['classifier']
18              content['children'].select do |child|
19                child['uri'] =~ %r{^/#{maven_data['module']}-#{maven_data['base_rev']}-(SNAPSHOT|(?:(?:[0-9]{8}.[0-9]{6})-(?:[0-9]+)))-#{maven_data['classifier']}\.#{maven_data['ext']}$} && !child['folder']
20              end
21            else
22              content['children'].select do |child|
23                child['uri'] =~ %r{^/#{maven_data['module']}-#{maven_data['base_rev']}-(SNAPSHOT|(?:(?:[0-9]{8}.[0-9]{6})-(?:[0-9]+)))\.#{maven_data['ext']}$} && !child['folder']
24              end
25            end
26
27     raise("Couldn't find any Artifactory artifacts") if uris.empty?
28
29     latest = uris.sort_by { |x| x['uri'] }.last['uri']
30     Puppet.debug("Latest artifact found for #{url} was #{latest}")
31
32     # Now GET the fileinfo endpoint of the resolved latest version file
33     uri = URI("#{content['uri']}#{latest}")
34     response = PuppetX::Bodeco::Util.content(uri)
35     content  = JSON.parse(response)
36
37     url  = content['downloadUri']
38     sha1 = content['checksums'] && content['checksums']['sha1']
39
40     {
41       'url'  => url,
42       'sha1' => sha1
43     }
44   end
45 end