-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub.py
More file actions
97 lines (76 loc) · 3.04 KB
/
Copy pathgithub.py
File metadata and controls
97 lines (76 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import json
import requests
from vcsrepository import VcsRepository
class Github:
base_url = 'https://api.github.com/'
login = ''
password = ''
def __init__(self, login, password):
"""Creates GitHub service instance.
:param str login: Username
:param str password: Personal access token
"""
self.login = login
self.password = password
def __request_api(self, endpoint, **kwargs):
"""Requests GitHub API.
:param str endpoint: API endpoint
:return: Request response
:rtype Any
"""
response = requests.request(url=self.base_url + endpoint,
auth=(self.login, self.password),
headers={'Accept': 'application/vnd.github.v3+json'},
**kwargs)
result = response.json()
if 'errors' in result:
raise Exception('GitHub API request failed: {}'.format(result['message']))
if not response.ok:
raise Exception('GitHub API request failed. Check your credentials and network connection')
return result
def get_repositories(self):
"""Gets repositories of a user.
:return:
:rtype list of VcsRepository
"""
repositories_raw_data = self.__request_api('user/repos?affiliation=owner&per_page=100', method='GET')
repositories = []
for datum in repositories_raw_data:
repositories.append(VcsRepository(datum['name'], datum['description'], datum['html_url'], datum['private']))
return repositories
def create_repository(self, vcs_repository):
"""Creates repository on GitHub.
:param VcsRepository vcs_repository: Repository data
:return: Created repository
:rtype VcsRepository
"""
repository_data = {
'name': vcs_repository.name,
'description': self.__normalize_description(vcs_repository.description),
'private': vcs_repository.is_private
}
response = self.__request_api('user/repos', data=json.dumps(repository_data), method='POST')
return VcsRepository(vcs_repository.name,
vcs_repository.description,
response['ssh_url'],
vcs_repository.is_private)
def repository_exists(self, vcs_repository):
"""Checks whether a repository exists
:param VcsRepository vcs_repository: Repository to check
:return: Whether repository exists
:rtype bool
"""
try:
self.__request_api('repos/{}/{}'.format(self.login, vcs_repository.name), method='GET')
return True
except:
pass
return False
@staticmethod
def __normalize_description(description):
"""Removes control characters from repository description.
:param string description:
:return: Normalized description
:rtype string
"""
return ' '.join(description.split())