Skip to content

Commit def6a1c

Browse files
committed
Document, expand, and fix sudo usage
Fix bugs with add and find functions. Add 'with' statement usage.
1 parent 47f0420 commit def6a1c

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ for event in gl.project(1).events(limit=10): # 10 most recent events
3838
for project in gl.projects(page=1, per_page=10): # pagination
3939
print project.issues(limit=1)[0].title # (assume issue[0] exists...)
4040

41+
#
42+
# Sudo usage examples (GitLab v6.1+)
43+
# All functions accept an optional, undocumented, 'sudo' argument
44+
# specifiying a username or user id to act as.
45+
#
46+
gl.get_current_user(sudo='other_user') # => 'other_user' CurrentUser object
47+
gl.projects(sudo=2) # => list of user 2's projects
48+
with gl.sudo('other_user'):
49+
gl.get_current_user() # => 'other_user' CurrentUser object
50+
gl.projects() # => list of 'other_users's projects
4151

4252
#
4353
# Example usage involving users

gitlab3/__init__.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,14 @@ def fn(**kwargs):
133133
del kwargs['find_all']
134134
except KeyError:
135135
find_all = False
136+
try:
137+
query_data = {}
138+
query_data['sudo'] = kwargs['sudo']
139+
del kwargs['sudo']
140+
except KeyError:
141+
pass
136142
if not objects:
137-
objects = _query_list(api, parent, {})
143+
objects = _query_list(api, parent, query_data)
138144

139145
return _find_matches(objects, kwargs, find_all)
140146
setattr(parent, 'find_' + name, fn)
@@ -256,6 +262,8 @@ def _add_api(definition, parent):
256262
else:
257263
uq_url = parent._uq_url
258264
uq_url += re.sub(r'/\:.*', '', url) # "unqualify" the url
265+
# 'sudo' is an optional parameter for all functions
266+
definition.optional_params.append('sudo')
259267

260268
cls_attrs = {
261269
'_key_name': definition.key_name,
@@ -466,3 +474,14 @@ def login(self, login_or_email, password):
466474
headers = {'PRIVATE-TOKEN': ret['private_token']}
467475
setattr(_GitLabAPI, '_headers', headers)
468476
return True
477+
478+
class sudo:
479+
"""Alternative sudo usage. To be used with the 'with' statement"""
480+
def __init__(self, username_or_id):
481+
self.user = username_or_id
482+
def __enter__(self):
483+
headers = getattr(_GitLabAPI, '_headers')
484+
headers['SUDO'] = self.user
485+
def __exit__(self, type, value, traceback):
486+
headers = getattr(_GitLabAPI, '_headers')
487+
del headers['SUDO']

0 commit comments

Comments
 (0)