4
4
by Itxaka Serrano Garcia <itxakaserrano@gmail.com>
5
5
Check the license on the LICENSE file
6
6
"""
7
- import warnings
8
-
9
7
import requests
10
8
11
9
from . import exceptions
12
-
13
- from six . moves . urllib . parse import quote_plus
10
+ from . session import Session
11
+ from . helper import deprecated , format_string
14
12
15
13
16
- def deprecated (func ):
17
- """
18
- This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted
19
- when the function is used.
20
-
21
- :param func: The function to run
22
- :return: function
23
- """
24
- def deprecation_warning (* args , ** kwargs ):
25
- warnings .warn ('Call to deprecated function {name}. Please consult our documentation at '
26
- 'http://pyapi-gitlab.readthedocs.io/en/latest/#gitlab.Gitlab.{name}' .format (name = func .__name__ ),
27
- category = DeprecationWarning )
28
- return func (* args , ** kwargs )
29
- deprecation_warning .__name__ = func .__name__
30
- deprecation_warning .__doc__ = func .__doc__
31
- deprecation_warning .__dict__ = func .__dict__
32
- return deprecation_warning
33
-
34
-
35
- class Gitlab (object ):
14
+ class Gitlab (Session ):
36
15
"""
37
16
Gitlab class
38
17
@@ -47,171 +26,6 @@ class Gitlab(object):
47
26
:class:`requests.exceptions.HTTPError` exceptions on failure
48
27
:return: None
49
28
"""
50
- def __init__ (self , host , token = None , oauth_token = None , verify_ssl = True , auth = None , timeout = None ,
51
- suppress_http_error = True ):
52
- self .suppress_http_error = suppress_http_error
53
-
54
- if token :
55
- self .token = token
56
- self .headers = {'PRIVATE-TOKEN' : self .token }
57
-
58
- if oauth_token :
59
- self .oauth_token = oauth_token
60
- self .headers = {'Authorization' : 'Bearer {}' .format (
61
- self .oauth_token )}
62
-
63
- if not host :
64
- raise ValueError ('host argument may not be empty' )
65
-
66
- self .host = host .rstrip ('/' )
67
-
68
- if self .host .startswith ('http://' ) or self .host .startswith ('https://' ):
69
- pass
70
- else :
71
- self .host = 'https://' + self .host
72
-
73
- self .auth = auth
74
- self .api_url = self .host + '/api/v3'
75
- self .projects_url = self .api_url + '/projects'
76
- self .users_url = self .api_url + '/users'
77
- self .keys_url = self .api_url + '/user/keys'
78
- self .groups_url = self .api_url + '/groups'
79
- self .search_url = self .api_url + '/projects/search'
80
- self .hook_url = self .api_url + '/hooks'
81
- self .namespaces_url = self .api_url + '/namespaces'
82
- self .verify_ssl = verify_ssl
83
- self .timeout = timeout
84
-
85
- def get (self , uri , default_response = None , ** kwargs ):
86
- """
87
- Call GET on the Gitlab server
88
-
89
- >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
90
- >>> gitlab.login(user='root', password='5iveL!fe')
91
- >>> gitlab.get('/users/5')
92
-
93
- :param uri: String with the URI for the endpoint to GET from
94
- :param default_response: Return value if JSONDecodeError
95
- :param kwargs: Key word arguments to use as GET arguments
96
- :return: Dictionary containing response data
97
- :raise: HttpError: If invalid response returned
98
- """
99
- url = self .api_url + uri
100
- response = requests .get (url , params = kwargs , headers = self .headers ,
101
- verify = self .verify_ssl , auth = self .auth ,
102
- timeout = self .timeout )
103
-
104
- return self .success_or_raise (response , default_response = default_response )
105
-
106
- def post (self , uri , default_response = None , ** kwargs ):
107
- """
108
- Call POST on the Gitlab server
109
-
110
- >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
111
- >>> gitlab.login(user='root', password='5iveL!fe')
112
- >>> password = 'MyTestPassword1'
113
- >>> email = 'example@example.com'
114
- >>> data = {'name': 'test', 'username': 'test1', 'password': password, 'email': email}
115
- >>> gitlab.post('/users/5', **data)
116
-
117
- :param uri: String with the URI for the endpoint to POST to
118
- :param default_response: Return value if JSONDecodeError
119
- :param kwargs: Key word arguments representing the data to use in the POST
120
- :return: Dictionary containing response data
121
- :raise: HttpError: If invalid response returned
122
- """
123
- url = self .api_url + uri
124
-
125
- response = requests .post (
126
- url , headers = self .headers , data = kwargs ,
127
- verify = self .verify_ssl , auth = self .auth , timeout = self .timeout )
128
-
129
- return self .success_or_raise (response , default_response = default_response )
130
-
131
- def delete (self , uri , default_response = None ):
132
- """
133
- Call DELETE on the Gitlab server
134
-
135
- >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
136
- >>> gitlab.login(user='root', password='5iveL!fe')
137
- >>> gitlab.delete('/users/5')
138
-
139
- :param uri: String with the URI you wish to delete
140
- :param default_response: Return value if JSONDecodeError
141
- :return: Dictionary containing response data
142
- :raise: HttpError: If invalid response returned
143
- """
144
- url = self .api_url + uri
145
- response = requests .delete (
146
- url , headers = self .headers , verify = self .verify_ssl ,
147
- auth = self .auth , timeout = self .timeout )
148
-
149
- return self .success_or_raise (response , default_response = default_response )
150
-
151
- @staticmethod
152
- def _format_string (string ):
153
- """
154
- Formats a string so its ready for Gitlab or returns an int
155
-
156
- :param string: String to be formatted
157
- :return: Int or String
158
- """
159
- if isinstance (string , str ):
160
- return quote_plus (string )
161
- return string
162
-
163
- def success_or_raise (self , response , default_response = None ):
164
- """
165
- Check if request was successful or raises an HttpError
166
-
167
- :param response: Response Object to check
168
- :param default_response: Return value if JSONDecodeError
169
- :returns dict: Dictionary containing response data
170
- :returns bool: :obj:`False` on failure when exceptions are suppressed
171
- :raises requests.exceptions.HTTPError: If invalid response returned
172
- """
173
- if self .suppress_http_error and not response .ok :
174
- return False
175
-
176
- response_json = default_response
177
- if response_json is None :
178
- response_json = {}
179
-
180
- response .raise_for_status ()
181
-
182
- try :
183
- response_json = response .json ()
184
- except ValueError :
185
- pass
186
-
187
- return response_json
188
-
189
- def login (self , email = None , password = None , user = None ):
190
- """
191
- Logs the user in and setups the header with the private token
192
-
193
- :param email: Gitlab user Email
194
- :param user: Gitlab username
195
- :param password: Gitlab user password
196
- :return: True if login successful
197
- :raise: HttpError
198
- :raise: ValueError
199
- """
200
- if user is not None :
201
- data = {'login' : user , 'password' : password }
202
- elif email is not None :
203
- data = {'email' : email , 'password' : password }
204
- else :
205
- raise ValueError ('Neither username nor email provided to login' )
206
-
207
- self .headers = {'connection' : 'close' }
208
- response = self .post ('/session' , ** data )
209
-
210
- self .token = response ['private_token' ]
211
- self .headers = {'PRIVATE-TOKEN' : self .token ,
212
- 'connection' : 'close' }
213
- return response
214
-
215
29
def setsudo (self , user = None ):
216
30
"""
217
31
Set the subsequent API calls to the user provided
@@ -536,7 +350,7 @@ def get_project(self, project):
536
350
:return: Dictionary containing the Project
537
351
:raise: HttpError: If invalid response returned
538
352
"""
539
- project = self . _format_string (project )
353
+ project = format_string (project )
540
354
541
355
return self .get (
542
356
'/projects/{project}' .format (project = project ))
@@ -2681,30 +2495,3 @@ def getnamespaces(self, search=None, page=1, per_page=20):
2681
2495
return request .json ()
2682
2496
else :
2683
2497
return False
2684
-
2685
- @staticmethod
2686
- def getall (fn , page = None , * args , ** kwargs ):
2687
- """
2688
- Auto-iterate over the paginated results of various methods of the API.
2689
- Pass the GitLabAPI method as the first argument, followed by the
2690
- other parameters as normal. Include `page` to determine first page to poll.
2691
- Remaining kwargs are passed on to the called method, including `per_page`.
2692
-
2693
- :param fn: Actual method to call
2694
- :param page: Optional, page number to start at, defaults to 1
2695
- :param args: Positional arguments to actual method
2696
- :param kwargs: Keyword arguments to actual method
2697
- :return: Yields each item in the result until exhausted, and then implicit StopIteration; or no elements if error
2698
- """
2699
- if not page :
2700
- page = 1
2701
-
2702
- while True :
2703
- results = fn (* args , page = page , ** kwargs )
2704
-
2705
- if not results :
2706
- break
2707
- for x in results :
2708
- yield x
2709
-
2710
- page += 1
0 commit comments