1
2 __author__ = 'ggegiya1'
3 import tempfile
4 import os
5 import requests
6
7
9 """
10 Helper class to facilitate interacting with Artifactory
11 """
12
13 build_server_url = 'http://artifactory.ypdev.ca/artifactory'
14 repository = ''
15 group_id = ''
16
17 - def __init__(self, repository, group_id):
18 """
19 Constructor method
20 :param repository: (str) Name of the repo in Artifactory (ie: libs-release-local)
21 :param group_id: (str) Name of the group in Artifactory (ie: com.ypg.yid)
22 """
23
24 self.repository = repository
25 self.group_id = group_id
26
28 """
29 Retrieve all the available versions for the specified artifact
30 :param artifact_id: (str) name of the artifact in Artifactory
31 :return: (list) A list of versions sorted from latest to oldest
32 """
33
34 versions_url = "{url}/api/search/versions?g={group_id}&a={artifact_id}&repos={repository}"
35 versions_url = versions_url.format(url=self.build_server_url, group_id=self.group_id,
36 artifact_id=artifact_id, repository=self.repository)
37 resp = requests.get(versions_url)
38 versions = resp.json()
39 if hasattr(versions, "__iter__"):
40 return map(lambda x: x["version"], versions["results"])
41 return []
42
43 - def get_artifact(self, artifact_id, version, criteria=None):
44 """
45 Fetches the artifact from Artifactory and write the file to disk. A criteria can be added to help
46 :param artifact_id: (str) name of the artifact in Artifactory
47 :param version: (str) numeric representation of the artifact version
48 :param criteria: (str) a filter criteria for choosing the artifact to download (ex: .jar, -QA.msi)
49 :return: (list) a list of successfully downloaded files
50 """
51
52 search_url = "{url}/api/search/gavc?a={artifact_id}&v={version}"
53 search_url = search_url.format(url=self.build_server_url,
54 artifact_id=artifact_id, version=version)
55 temp = requests.get(search_url, stream=True)
56
57 resp = temp.json()['results']
58
59 to_download = []
60 downloaded = []
61 if criteria:
62 for url in resp:
63 if criteria in url['uri']:
64 to_download.append(url['uri'])
65 else:
66 for url in resp:
67 to_download.append(url['uri'])
68
69 for download in to_download:
70 filename = download.split('/')[-1]
71 file = os.path.join(tempfile.gettempdir(), filename)
72 download_url = self.build_server_url+download.split('storage')[1]
73 headers = {'Accept-Encoding': 'identity, deflate, compress', 'Accept': '*/*',
74 'User-Agent': 'python-requests/1.2.0'}
75 if '.msi' not in filename:
76 temp = requests.get(download_url, stream=True, headers=headers)
77 with open(file, 'wb') as f:
78 f.write(temp.raw.data)
79
80 if os.path.exists(file):
81 downloaded.append(file)
82
83 return downloaded
84
86 """
87 Removes the specified files
88 :param downloads: (list) a list of files to delete
89 :return: (bool) If files were removed or not
90 """
91 for file in downloads:
92 try:
93 os.remove(file)
94 except OSError:
95 return False
96 return True
97