diff options
Diffstat (limited to 'gitlab/v4/objects.py')
| -rw-r--r-- | gitlab/v4/objects.py | 3012 |
1 files changed, 1497 insertions, 1515 deletions
diff --git a/gitlab/v4/objects.py b/gitlab/v4/objects.py index 89321c9..49ccc9d 100644 --- a/gitlab/v4/objects.py +++ b/gitlab/v4/objects.py @@ -16,17 +16,14 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function -from __future__ import division from __future__ import absolute_import import base64 -import json import six -from six.moves import urllib -import gitlab from gitlab.base import * # noqa from gitlab.exceptions import * # noqa +from gitlab.mixins import * # noqa from gitlab import utils VISIBILITY_PRIVATE = 'private' @@ -40,587 +37,623 @@ ACCESS_MASTER = 40 ACCESS_OWNER = 50 -class SidekiqManager(object): +class SidekiqManager(RESTManager): """Manager for the Sidekiq methods. This manager doesn't actually manage objects but provides helper fonction for the sidekiq metrics API. """ - def __init__(self, gl): - """Constructs a Sidekiq manager. + + @exc.on_http_error(exc.GitlabGetError) + def queue_metrics(self, **kwargs): + """Return the registred queues information. Args: - gl (gitlab.Gitlab): Gitlab object referencing the GitLab server. - """ - self.gitlab = gl + **kwargs: Extra options to send to the server (e.g. sudo) - def _simple_get(self, url, **kwargs): - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return r.json() + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the information couldn't be retrieved - def queue_metrics(self, **kwargs): - """Returns the registred queues information.""" - return self._simple_get('/sidekiq/queue_metrics', **kwargs) + Returns: + dict: Information about the Sidekiq queues + """ + return self.gitlab.http_get('/sidekiq/queue_metrics', **kwargs) + @exc.on_http_error(exc.GitlabGetError) def process_metrics(self, **kwargs): - """Returns the registred sidekiq workers.""" - return self._simple_get('/sidekiq/process_metrics', **kwargs) + """Return the registred sidekiq workers. + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the information couldn't be retrieved + + Returns: + dict: Information about the register Sidekiq worker + """ + return self.gitlab.http_get('/sidekiq/process_metrics', **kwargs) + + @exc.on_http_error(exc.GitlabGetError) def job_stats(self, **kwargs): - """Returns statistics about the jobs performed.""" - return self._simple_get('/sidekiq/job_stats', **kwargs) + """Return statistics about the jobs performed. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the information couldn't be retrieved + + Returns: + dict: Statistics about the Sidekiq jobs performed + """ + return self.gitlab.http_get('/sidekiq/job_stats', **kwargs) + @exc.on_http_error(exc.GitlabGetError) def compound_metrics(self, **kwargs): - """Returns all available metrics and statistics.""" - return self._simple_get('/sidekiq/compound_metrics', **kwargs) - - -class UserEmail(GitlabObject): - _url = '/users/%(user_id)s/emails' - canUpdate = False - shortPrintAttr = 'email' - requiredUrlAttrs = ['user_id'] - requiredCreateAttrs = ['email'] - - -class UserEmailManager(BaseManager): - obj_cls = UserEmail - - -class UserKey(GitlabObject): - _url = '/users/%(user_id)s/keys' - canGet = 'from_list' - canUpdate = False - requiredUrlAttrs = ['user_id'] - requiredCreateAttrs = ['title', 'key'] - - -class UserKeyManager(BaseManager): - obj_cls = UserKey - - -class UserProject(GitlabObject): - _url = '/projects/user/%(user_id)s' - _constructorTypes = {'owner': 'User', 'namespace': 'Group'} - canUpdate = False - canDelete = False - canList = False - canGet = False - requiredUrlAttrs = ['user_id'] - requiredCreateAttrs = ['name'] - optionalCreateAttrs = ['default_branch', 'issues_enabled', 'wall_enabled', - 'merge_requests_enabled', 'wiki_enabled', - 'snippets_enabled', 'public', 'visibility', - 'description', 'builds_enabled', 'public_builds', - 'import_url', 'only_allow_merge_if_build_succeeds'] - - -class UserProjectManager(BaseManager): - obj_cls = UserProject - - -class User(GitlabObject): - _url = '/users' - shortPrintAttr = 'username' - optionalListAttrs = ['active', 'blocked', 'username', 'extern_uid', - 'provider', 'external'] - requiredCreateAttrs = ['email', 'username', 'name'] - optionalCreateAttrs = ['password', 'reset_password', 'skype', 'linkedin', - 'twitter', 'projects_limit', 'extern_uid', - 'provider', 'bio', 'admin', 'can_create_group', - 'website_url', 'skip_confirmation', 'external', - 'organization', 'location'] - requiredUpdateAttrs = ['email', 'username', 'name'] - optionalUpdateAttrs = ['password', 'skype', 'linkedin', 'twitter', - 'projects_limit', 'extern_uid', 'provider', 'bio', - 'admin', 'can_create_group', 'website_url', - 'skip_confirmation', 'external', 'organization', - 'location'] - managers = ( - ('emails', 'UserEmailManager', [('user_id', 'id')]), - ('keys', 'UserKeyManager', [('user_id', 'id')]), - ('projects', 'UserProjectManager', [('user_id', 'id')]), + """Return all available metrics and statistics. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the information couldn't be retrieved + + Returns: + dict: All available Sidekiq metrics and statistics + """ + return self.gitlab.http_get('/sidekiq/compound_metrics', **kwargs) + + +class UserEmail(ObjectDeleteMixin, RESTObject): + _short_print_attr = 'email' + + +class UserEmailManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager): + _path = '/users/%(user_id)s/emails' + _obj_cls = UserEmail + _from_parent_attrs = {'user_id': 'id'} + _create_attrs = (('email', ), tuple()) + + +class UserKey(ObjectDeleteMixin, RESTObject): + pass + + +class UserKeyManager(GetFromListMixin, CreateMixin, DeleteMixin, RESTManager): + _path = '/users/%(user_id)s/keys' + _obj_cls = UserKey + _from_parent_attrs = {'user_id': 'id'} + _create_attrs = (('title', 'key'), tuple()) + + +class UserProject(RESTObject): + _constructor_types = {'owner': 'User', 'namespace': 'Group'} + + +class UserProjectManager(CreateMixin, RESTManager): + _path = '/projects/user/%(user_id)s' + _obj_cls = UserProject + _from_parent_attrs = {'user_id': 'id'} + _create_attrs = ( + ('name', ), + ('default_branch', 'issues_enabled', 'wall_enabled', + 'merge_requests_enabled', 'wiki_enabled', 'snippets_enabled', + 'public', 'visibility', 'description', 'builds_enabled', + 'public_builds', 'import_url', 'only_allow_merge_if_build_succeeds') ) - def _data_for_gitlab(self, extra_parameters={}, update=False, - as_json=True): - if hasattr(self, 'confirm'): - self.confirm = str(self.confirm).lower() - return super(User, self)._data_for_gitlab(extra_parameters) +class User(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'username' + _managers = ( + ('emails', 'UserEmailManager'), + ('keys', 'UserKeyManager'), + ('projects', 'UserProjectManager'), + ) + + @exc.on_http_error(exc.GitlabBlockError) def block(self, **kwargs): - """Blocks the user.""" - url = '/users/%s/block' % self.id - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabBlockError, 201) - self.state = 'blocked' + """Block the user. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabBlockError: If the user could not be blocked + + Returns: + bool: Whether the user status has been changed + """ + path = '/users/%s/block' % self.id + server_data = self.manager.gitlab.http_post(path, **kwargs) + if server_data is True: + self._attrs['state'] = 'blocked' + return server_data + @exc.on_http_error(exc.GitlabUnblockError) def unblock(self, **kwargs): - """Unblocks the user.""" - url = '/users/%s/unblock' % self.id - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabUnblockError, 201) - self.state = 'active' + """Unblock the user. - def __eq__(self, other): - if type(other) is type(self): - selfdict = self.as_dict() - otherdict = other.as_dict() - selfdict.pop('password', None) - otherdict.pop('password', None) - return selfdict == otherdict - return False + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabUnblockError: If the user could not be unblocked + Returns: + bool: Whether the user status has been changed + """ + path = '/users/%s/unblock' % self.id + server_data = self.manager.gitlab.http_post(path, **kwargs) + if server_data is True: + self._attrs['state'] = 'active' + return server_data + + +class UserManager(CRUDMixin, RESTManager): + _path = '/users' + _obj_cls = User + + _list_filters = ('active', 'blocked', 'username', 'extern_uid', 'provider', + 'external') + _create_attrs = ( + ('email', 'username', 'name'), + ('password', 'reset_password', 'skype', 'linkedin', 'twitter', + 'projects_limit', 'extern_uid', 'provider', 'bio', 'admin', + 'can_create_group', 'website_url', 'skip_confirmation', 'external', + 'organization', 'location') + ) + _update_attrs = ( + ('email', 'username', 'name'), + ('password', 'skype', 'linkedin', 'twitter', 'projects_limit', + 'extern_uid', 'provider', 'bio', 'admin', 'can_create_group', + 'website_url', 'skip_confirmation', 'external', 'organization', + 'location') + ) -class UserManager(BaseManager): - obj_cls = User + def _sanitize_data(self, data, action): + new_data = data.copy() + if 'confirm' in data: + new_data['confirm'] = str(new_data['confirm']).lower() + return new_data -class CurrentUserEmail(GitlabObject): - _url = '/user/emails' - canUpdate = False - shortPrintAttr = 'email' - requiredCreateAttrs = ['email'] +class CurrentUserEmail(ObjectDeleteMixin, RESTObject): + _short_print_attr = 'email' -class CurrentUserEmailManager(BaseManager): - obj_cls = CurrentUserEmail +class CurrentUserEmailManager(RetrieveMixin, CreateMixin, DeleteMixin, + RESTManager): + _path = '/user/emails' + _obj_cls = CurrentUserEmail + _create_attrs = (('email', ), tuple()) -class CurrentUserKey(GitlabObject): - _url = '/user/keys' - canUpdate = False - shortPrintAttr = 'title' - requiredCreateAttrs = ['title', 'key'] +class CurrentUserKey(ObjectDeleteMixin, RESTObject): + _short_print_attr = 'title' -class CurrentUserKeyManager(BaseManager): - obj_cls = CurrentUserKey +class CurrentUserKeyManager(RetrieveMixin, CreateMixin, DeleteMixin, + RESTManager): + _path = '/user/keys' + _obj_cls = CurrentUserKey + _create_attrs = (('title', 'key'), tuple()) -class CurrentUser(GitlabObject): - _url = '/user' - canList = False - canCreate = False - canUpdate = False - canDelete = False - shortPrintAttr = 'username' - managers = ( - ('emails', 'CurrentUserEmailManager', [('user_id', 'id')]), - ('keys', 'CurrentUserKeyManager', [('user_id', 'id')]), +class CurrentUser(RESTObject): + _id_attr = None + _short_print_attr = 'username' + _managers = ( + ('emails', 'CurrentUserEmailManager'), + ('keys', 'CurrentUserKeyManager'), ) -class ApplicationSettings(GitlabObject): - _url = '/application/settings' - _id_in_update_url = False - getRequiresId = False - optionalUpdateAttrs = ['after_sign_out_path', - 'container_registry_token_expire_delay', - 'default_branch_protection', - 'default_project_visibility', - 'default_projects_limit', - 'default_snippet_visibility', - 'domain_blacklist', - 'domain_blacklist_enabled', - 'domain_whitelist', - 'enabled_git_access_protocol', - 'gravatar_enabled', - 'home_page_url', - 'max_attachment_size', - 'repository_storage', - 'restricted_signup_domains', - 'restricted_visibility_levels', - 'session_expire_delay', - 'sign_in_text', - 'signin_enabled', - 'signup_enabled', - 'twitter_sharing_enabled', - 'user_oauth_applications'] - canList = False - canCreate = False - canDelete = False - - def _data_for_gitlab(self, extra_parameters={}, update=False, - as_json=True): - data = (super(ApplicationSettings, self) - ._data_for_gitlab(extra_parameters, update=update, - as_json=False)) - if not self.domain_whitelist: - data.pop('domain_whitelist', None) - return json.dumps(data) - - -class ApplicationSettingsManager(BaseManager): - obj_cls = ApplicationSettings - - -class BroadcastMessage(GitlabObject): - _url = '/broadcast_messages' - requiredCreateAttrs = ['message'] - optionalCreateAttrs = ['starts_at', 'ends_at', 'color', 'font'] - requiredUpdateAttrs = [] - optionalUpdateAttrs = ['message', 'starts_at', 'ends_at', 'color', 'font'] - - -class BroadcastMessageManager(BaseManager): - obj_cls = BroadcastMessage - - -class DeployKey(GitlabObject): - _url = '/deploy_keys' - canGet = 'from_list' - canCreate = False - canUpdate = False - canDelete = False - - -class DeployKeyManager(BaseManager): - obj_cls = DeployKey - - -class NotificationSettings(GitlabObject): - _url = '/notification_settings' - _id_in_update_url = False - getRequiresId = False - optionalUpdateAttrs = ['level', - 'notification_email', - 'new_note', - 'new_issue', - 'reopen_issue', - 'close_issue', - 'reassign_issue', - 'new_merge_request', - 'reopen_merge_request', - 'close_merge_request', - 'reassign_merge_request', - 'merge_merge_request'] - canList = False - canCreate = False - canDelete = False - - -class NotificationSettingsManager(BaseManager): - obj_cls = NotificationSettings - - -class Dockerfile(GitlabObject): - _url = '/templates/dockerfiles' - canDelete = False - canUpdate = False - canCreate = False - idAttr = 'name' - - -class DockerfileManager(BaseManager): - obj_cls = Dockerfile - - -class Gitignore(GitlabObject): - _url = '/templates/gitignores' - canDelete = False - canUpdate = False - canCreate = False - idAttr = 'name' +class CurrentUserManager(GetWithoutIdMixin, RESTManager): + _path = '/user' + _obj_cls = CurrentUser + def credentials_auth(self, email, password): + data = {'email': email, 'password': password} + server_data = self.gitlab.http_post('/session', post_data=data) + return CurrentUser(self, server_data) -class GitignoreManager(BaseManager): - obj_cls = Gitignore +class ApplicationSettings(SaveMixin, RESTObject): + _id_attr = None -class Gitlabciyml(GitlabObject): - _url = '/templates/gitlab_ci_ymls' - canDelete = False - canUpdate = False - canCreate = False - idAttr = 'name' +class ApplicationSettingsManager(GetWithoutIdMixin, UpdateMixin, RESTManager): + _path = '/application/settings' + _obj_cls = ApplicationSettings + _update_attrs = ( + tuple(), + ('after_sign_out_path', 'container_registry_token_expire_delay', + 'default_branch_protection', 'default_project_visibility', + 'default_projects_limit', 'default_snippet_visibility', + 'domain_blacklist', 'domain_blacklist_enabled', 'domain_whitelist', + 'enabled_git_access_protocol', 'gravatar_enabled', 'home_page_url', + 'max_attachment_size', 'repository_storage', + 'restricted_signup_domains', 'restricted_visibility_levels', + 'session_expire_delay', 'sign_in_text', 'signin_enabled', + 'signup_enabled', 'twitter_sharing_enabled', + 'user_oauth_applications') + ) -class GitlabciymlManager(BaseManager): - obj_cls = Gitlabciyml + def _sanitize_data(self, data, action): + new_data = data.copy() + if 'domain_whitelist' in data and data['domain_whitelist'] is None: + new_data.pop('domain_whitelist') + return new_data -class GroupIssue(GitlabObject): - _url = '/groups/%(group_id)s/issues' - canGet = 'from_list' - canCreate = False - canUpdate = False - canDelete = False - requiredUrlAttrs = ['group_id'] - optionalListAttrs = ['state', 'labels', 'milestone', 'order_by', 'sort'] +class BroadcastMessage(SaveMixin, ObjectDeleteMixin, RESTObject): + pass -class GroupIssueManager(BaseManager): - obj_cls = GroupIssue +class BroadcastMessageManager(CRUDMixin, RESTManager): + _path = '/broadcast_messages' + _obj_cls = BroadcastMessage + _create_attrs = (('message', ), ('starts_at', 'ends_at', 'color', 'font')) + _update_attrs = (tuple(), ('message', 'starts_at', 'ends_at', 'color', + 'font')) -class GroupMember(GitlabObject): - _url = '/groups/%(group_id)s/members' - canGet = 'from_list' - requiredUrlAttrs = ['group_id'] - requiredCreateAttrs = ['access_level', 'user_id'] - optionalCreateAttrs = ['expires_at'] - requiredUpdateAttrs = ['access_level'] - optionalUpdateAttrs = ['expires_at'] - shortPrintAttr = 'username' - def _update(self, **kwargs): - self.user_id = self.id - super(GroupMember, self)._update(**kwargs) +class DeployKey(RESTObject): + pass -class GroupMemberManager(BaseManager): - obj_cls = GroupMember +class DeployKeyManager(GetFromListMixin, RESTManager): + _path = '/deploy_keys' + _obj_cls = DeployKey -class GroupNotificationSettings(NotificationSettings): - _url = '/groups/%(group_id)s/notification_settings' - requiredUrlAttrs = ['group_id'] +class NotificationSettings(SaveMixin, RESTObject): + _id_attr = None -class GroupNotificationSettingsManager(BaseManager): - obj_cls = GroupNotificationSettings +class NotificationSettingsManager(GetWithoutIdMixin, UpdateMixin, RESTManager): + _path = '/notification_settings' + _obj_cls = NotificationSettings + _update_attrs = ( + tuple(), + ('level', 'notification_email', 'new_note', 'new_issue', + 'reopen_issue', 'close_issue', 'reassign_issue', 'new_merge_request', + 'reopen_merge_request', 'close_merge_request', + 'reassign_merge_request', 'merge_merge_request') + ) -class GroupAccessRequest(GitlabObject): - _url = '/groups/%(group_id)s/access_requests' - canGet = 'from_list' - canUpdate = False - def approve(self, access_level=gitlab.DEVELOPER_ACCESS, **kwargs): - """Approve an access request. +class Dockerfile(RESTObject): + _id_attr = 'name' - Attrs: - access_level (int): The access level for the user. - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabUpdateError: If the server fails to perform the request. - """ +class DockerfileManager(RetrieveMixin, RESTManager): + _path = '/templates/dockerfiles' + _obj_cls = Dockerfile + + +class Gitignore(RESTObject): + _id_attr = 'name' + + +class GitignoreManager(RetrieveMixin, RESTManager): + _path = '/templates/gitignores' + _obj_cls = Gitignore + + +class Gitlabciyml(RESTObject): + _id_attr = 'name' + + +class GitlabciymlManager(RetrieveMixin, RESTManager): + _path = '/templates/gitlab_ci_ymls' + _obj_cls = Gitlabciyml + + +class GroupIssue(RESTObject): + pass + + +class GroupIssueManager(GetFromListMixin, RESTManager): + _path = '/groups/%(group_id)s/issues' + _obj_cls = GroupIssue + _from_parent_attrs = {'group_id': 'id'} + _list_filters = ('state', 'labels', 'milestone', 'order_by', 'sort') - url = ('/groups/%(group_id)s/access_requests/%(id)s/approve' % - {'group_id': self.group_id, 'id': self.id}) - data = {'access_level': access_level} - r = self.gitlab._raw_put(url, data=data, **kwargs) - raise_error_from_response(r, GitlabUpdateError, 201) - self._set_from_dict(r.json()) +class GroupMember(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'username' -class GroupAccessRequestManager(BaseManager): - obj_cls = GroupAccessRequest +class GroupMemberManager(GetFromListMixin, CreateMixin, UpdateMixin, + DeleteMixin, RESTManager): + _path = '/groups/%(group_id)s/members' + _obj_cls = GroupMember + _from_parent_attrs = {'group_id': 'id'} + _create_attrs = (('access_level', 'user_id'), ('expires_at', )) + _update_attrs = (('access_level', ), ('expires_at', )) -class Hook(GitlabObject): + +class GroupNotificationSettings(NotificationSettings): + pass + + +class GroupNotificationSettingsManager(NotificationSettingsManager): + _path = '/groups/%(group_id)s/notification_settings' + _obj_cls = GroupNotificationSettings + _from_parent_attrs = {'group_id': 'id'} + + +class GroupAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject): + pass + + +class GroupAccessRequestManager(GetFromListMixin, CreateMixin, DeleteMixin, + RESTManager): + _path = '/groups/%(group_id)s/access_requests' + _obj_cls = GroupAccessRequest + _from_parent_attrs = {'group_id': 'id'} + + +class Hook(ObjectDeleteMixin, RESTObject): _url = '/hooks' - canUpdate = False - requiredCreateAttrs = ['url'] - shortPrintAttr = 'url' + _short_print_attr = 'url' -class HookManager(BaseManager): - obj_cls = Hook +class HookManager(NoUpdateMixin, RESTManager): + _path = '/hooks' + _obj_cls = Hook + _create_attrs = (('url', ), tuple()) -class Issue(GitlabObject): +class Issue(RESTObject): _url = '/issues' - _constructorTypes = {'author': 'User', 'assignee': 'User', - 'milestone': 'ProjectMilestone'} - canGet = 'from_list' - canDelete = False - canUpdate = False - canCreate = False - shortPrintAttr = 'title' - optionalListAttrs = ['state', 'labels', 'order_by', 'sort'] - + _constructor_types = {'author': 'User', + 'assignee': 'User', + 'milestone': 'ProjectMilestone'} + _short_print_attr = 'title' -class IssueManager(BaseManager): - obj_cls = Issue +class IssueManager(GetFromListMixin, RESTManager): + _path = '/issues' + _obj_cls = Issue + _list_filters = ('state', 'labels', 'order_by', 'sort') -class License(GitlabObject): - _url = '/templates/licenses' - canDelete = False - canUpdate = False - canCreate = False - idAttr = 'key' - optionalListAttrs = ['popular'] - optionalGetAttrs = ['project', 'fullname'] +class License(RESTObject): + _id_attr = 'key' -class LicenseManager(BaseManager): - obj_cls = License +class LicenseManager(RetrieveMixin, RESTManager): + _path = '/templates/licenses' + _obj_cls = License + _list_filters = ('popular', ) + _optional_get_attrs = ('project', 'fullname') -class Snippet(GitlabObject): - _url = '/snippets' - _constructorTypes = {'author': 'User'} - requiredCreateAttrs = ['title', 'file_name', 'content'] - optionalCreateAttrs = ['lifetime', 'visibility'] - optionalUpdateAttrs = ['title', 'file_name', 'content', 'visibility'] - shortPrintAttr = 'title' +class Snippet(SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User'} + _short_print_attr = 'title' - def raw(self, streamed=False, action=None, chunk_size=1024, **kwargs): - """Return the raw content of a snippet. + @exc.on_http_error(exc.GitlabGetError) + def content(self, streamed=False, action=None, chunk_size=1024, **kwargs): + """Return the content of a snippet. Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for treatment. action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. - - Returns: - str: The snippet content. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the content could not be retrieved + + Returns: + str: The snippet content """ - url = ("/snippets/%(snippet_id)s/raw" % {'snippet_id': self.id}) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) + path = '/snippets/%s/raw' % self.get_id() + result = self.manager.gitlab.http_get(path, streamed=streamed, + **kwargs) + return utils.response_content(result, streamed, action, chunk_size) -class SnippetManager(BaseManager): - obj_cls = Snippet +class SnippetManager(CRUDMixin, RESTManager): + _path = '/snippets' + _obj_cls = Snippet + _create_attrs = (('title', 'file_name', 'content'), + ('lifetime', 'visibility')) + _update_attrs = (tuple(), + ('title', 'file_name', 'content', 'visibility')) def public(self, **kwargs): """List all the public snippets. Args: - all (bool): If True, return all the items, without pagination - **kwargs: Additional arguments to send to GitLab. + all (bool): If True the returned object will be a list + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabListError: If the list could not be retrieved Returns: - list(gitlab.Gitlab.Snippet): The list of snippets. + RESTObjectList: A generator for the snippets list """ - return self.gitlab._raw_list("/snippets/public", Snippet, **kwargs) + return self.list(path='/snippets/public', **kwargs) -class Namespace(GitlabObject): - _url = '/namespaces' - canGet = 'from_list' - canUpdate = False - canDelete = False - canCreate = False - optionalListAttrs = ['search'] +class Namespace(RESTObject): + pass -class NamespaceManager(BaseManager): - obj_cls = Namespace +class NamespaceManager(GetFromListMixin, RESTManager): + _path = '/namespaces' + _obj_cls = Namespace + _list_filters = ('search', ) -class ProjectBoardList(GitlabObject): - _url = '/projects/%(project_id)s/boards/%(board_id)s/lists' - requiredUrlAttrs = ['project_id', 'board_id'] - _constructorTypes = {'label': 'ProjectLabel'} - requiredCreateAttrs = ['label_id'] - requiredUpdateAttrs = ['position'] +class ProjectBoardList(SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'label': 'ProjectLabel'} -class ProjectBoardListManager(BaseManager): - obj_cls = ProjectBoardList +class ProjectBoardListManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/boards/%(board_id)s/lists' + _obj_cls = ProjectBoardList + _from_parent_attrs = {'project_id': 'project_id', + 'board_id': 'id'} + _create_attrs = (('label_id', ), tuple()) + _update_attrs = (('position', ), tuple()) -class ProjectBoard(GitlabObject): - _url = '/projects/%(project_id)s/boards' - requiredUrlAttrs = ['project_id'] - _constructorTypes = {'labels': 'ProjectBoardList'} - canGet = 'from_list' - canUpdate = False - canCreate = False - canDelete = False - managers = ( - ('lists', 'ProjectBoardListManager', - [('project_id', 'project_id'), ('board_id', 'id')]), - ) +class ProjectBoard(RESTObject): + _constructor_types = {'labels': 'ProjectBoardList'} + _managers = (('lists', 'ProjectBoardListManager'), ) -class ProjectBoardManager(BaseManager): - obj_cls = ProjectBoard +class ProjectBoardManager(GetFromListMixin, RESTManager): + _path = '/projects/%(project_id)s/boards' + _obj_cls = ProjectBoard + _from_parent_attrs = {'project_id': 'id'} -class ProjectBranch(GitlabObject): - _url = '/projects/%(project_id)s/repository/branches' - _constructorTypes = {'author': 'User', "committer": "User"} +class ProjectBranch(ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User', "committer": "User"} + _id_attr = 'name' - idAttr = 'name' - canUpdate = False - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['branch', 'ref'] + @exc.on_http_error(exc.GitlabProtectError) + def protect(self, developers_can_push=False, developers_can_merge=False, + **kwargs): + """Protect the branch. - def protect(self, protect=True, **kwargs): - """Protects the branch.""" - url = self._url % {'project_id': self.project_id} - action = 'protect' if protect else 'unprotect' - url = "%s/%s/%s" % (url, self.name, action) - r = self.gitlab._raw_put(url, data=None, content_type=None, **kwargs) - raise_error_from_response(r, GitlabProtectError) + Args: + developers_can_push (bool): Set to True if developers are allowed + to push to the branch + developers_can_merge (bool): Set to True if developers are allowed + to merge to the branch + **kwargs: Extra options to send to the server (e.g. sudo) - if protect: - self.protected = protect - else: - del self.protected + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabProtectError: If the branch could not be protected + """ + path = '%s/%s/protect' % (self.manager.path, self.get_id()) + post_data = {'developers_can_push': developers_can_push, + 'developers_can_merge': developers_can_merge} + self.manager.gitlab.http_put(path, post_data=post_data, **kwargs) + self._attrs['protected'] = True + @exc.on_http_error(exc.GitlabProtectError) def unprotect(self, **kwargs): - """Unprotects the branch.""" - self.protect(False, **kwargs) + """Unprotect the branch. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabProtectError: If the branch could not be unprotected + """ + path = '%s/%s/protect' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_put(path, **kwargs) + self._attrs['protected'] = False -class ProjectBranchManager(BaseManager): - obj_cls = ProjectBranch +class ProjectBranchManager(NoUpdateMixin, RESTManager): + _path = '/projects/%(project_id)s/repository/branches' + _obj_cls = ProjectBranch + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('branch', 'ref'), tuple()) -class ProjectJob(GitlabObject): - _url = '/projects/%(project_id)s/jobs' - _constructorTypes = {'user': 'User', - 'commit': 'ProjectCommit', - 'runner': 'Runner'} - requiredUrlAttrs = ['project_id'] - canDelete = False - canUpdate = False - canCreate = False +class ProjectJob(RESTObject): + _constructor_types = {'user': 'User', + 'commit': 'ProjectCommit', + 'runner': 'Runner'} + @exc.on_http_error(exc.GitlabJobCancelError) def cancel(self, **kwargs): - """Cancel the job.""" - url = '/projects/%s/jobs/%s/cancel' % (self.project_id, self.id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabJobCancelError, 201) + """Cancel the job. + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabJobCancelError: If the job could not be canceled + """ + path = '%s/%s/cancel' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + + @exc.on_http_error(exc.GitlabJobRetryError) def retry(self, **kwargs): - """Retry the job.""" - url = '/projects/%s/jobs/%s/retry' % (self.project_id, self.id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabJobRetryError, 201) + """Retry the job. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabJobRetryError: If the job could not be retried + """ + path = '%s/%s/retry' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + @exc.on_http_error(exc.GitlabJobPlayError) def play(self, **kwargs): - """Trigger a job explicitly.""" - url = '/projects/%s/jobs/%s/play' % (self.project_id, self.id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabJobPlayError) + """Trigger a job explicitly. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabJobPlayError: If the job could not be triggered + """ + path = '%s/%s/play' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + + @exc.on_http_error(exc.GitlabJobEraseError) def erase(self, **kwargs): - """Erase the job (remove job artifacts and trace).""" - url = '/projects/%s/jobs/%s/erase' % (self.project_id, self.id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabJobEraseError, 201) + """Erase the job (remove job artifacts and trace). + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabJobEraseError: If the job could not be erased + """ + path = '%s/%s/erase' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + @exc.on_http_error(exc.GitlabCreateError) def keep_artifacts(self, **kwargs): - """Prevent artifacts from being delete when expiration is set. + """Prevent artifacts from being deleted when expiration is set. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabCreateError: If the request failed. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the request could not be performed """ - url = ('/projects/%s/jobs/%s/artifacts/keep' % - (self.project_id, self.id)) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabGetError, 200) + path = '%s/%s/artifacts/keep' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + @exc.on_http_error(exc.GitlabGetError) def artifacts(self, streamed=False, action=None, chunk_size=1024, **kwargs): """Get the job artifacts. @@ -628,447 +661,325 @@ class ProjectJob(GitlabObject): Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for - treatment. + treatment action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the artifacts could not be retrieved Returns: str: The artifacts if `streamed` is False, None otherwise. - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the artifacts are not available. """ - url = '/projects/%s/jobs/%s/artifacts' % (self.project_id, self.id) - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError, 200) - return utils.response_content(r, streamed, action, chunk_size) + path = '%s/%s/artifacts' % (self.manager.path, self.get_id()) + result = self.manager.gitlab.get_http(path, streamed=streamed, + **kwargs) + return utils.response_content(result, streamed, action, chunk_size) + @exc.on_http_error(exc.GitlabGetError) def trace(self, streamed=False, action=None, chunk_size=1024, **kwargs): """Get the job trace. Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for - treatment. + treatment action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. - - Returns: - str: The trace. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the trace is not available. - """ - url = '/projects/%s/jobs/%s/trace' % (self.project_id, self.id) - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError, 200) - return utils.response_content(r, streamed, action, chunk_size) - - -class ProjectJobManager(BaseManager): - obj_cls = ProjectJob - - -class ProjectCommitStatus(GitlabObject): - _url = '/projects/%(project_id)s/repository/commits/%(commit_id)s/statuses' - _create_url = '/projects/%(project_id)s/statuses/%(commit_id)s' - canUpdate = False - canDelete = False - requiredUrlAttrs = ['project_id', 'commit_id'] - optionalGetAttrs = ['ref_name', 'stage', 'name', 'all'] - requiredCreateAttrs = ['state'] - optionalCreateAttrs = ['description', 'name', 'context', 'ref', - 'target_url'] - - -class ProjectCommitStatusManager(BaseManager): - obj_cls = ProjectCommitStatus - - -class ProjectCommitComment(GitlabObject): - _url = '/projects/%(project_id)s/repository/commits/%(commit_id)s/comments' - canUpdate = False - canGet = False - canDelete = False - requiredUrlAttrs = ['project_id', 'commit_id'] - requiredCreateAttrs = ['note'] - optionalCreateAttrs = ['path', 'line', 'line_type'] - - -class ProjectCommitCommentManager(BaseManager): - obj_cls = ProjectCommitComment - - -class ProjectCommit(GitlabObject): - _url = '/projects/%(project_id)s/repository/commits' - canDelete = False - canUpdate = False - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['branch', 'commit_message', 'actions'] - optionalCreateAttrs = ['author_email', 'author_name'] - shortPrintAttr = 'title' - managers = ( - ('comments', 'ProjectCommitCommentManager', - [('project_id', 'project_id'), ('commit_id', 'id')]), - ('statuses', 'ProjectCommitStatusManager', - [('project_id', 'project_id'), ('commit_id', 'id')]), - ) - - def diff(self, **kwargs): - """Generate the commit diff.""" - url = ('/projects/%(project_id)s/repository/commits/%(commit_id)s/diff' - % {'project_id': self.project_id, 'commit_id': self.id}) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - - return r.json() - - def blob(self, filepath, streamed=False, action=None, chunk_size=1024, - **kwargs): - """Generate the content of a file for this commit. - - Args: - filepath (str): Path of the file to request. - streamed (bool): If True the data will be processed by chunks of - `chunk_size` and each chunk is passed to `action` for - treatment. - action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the artifacts could not be retrieved Returns: - str: The content of the file - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + str: The trace """ - url = ('/projects/%(project_id)s/repository/blobs/%(commit_id)s' % - {'project_id': self.project_id, 'commit_id': self.id}) - url += '?filepath=%s' % filepath - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) + path = '%s/%s/trace' % (self.manager.path, self.get_id()) + result = self.manager.gitlab.get_http(path, streamed=streamed, + **kwargs) + return utils.response_content(result, streamed, action, chunk_size) - def cherry_pick(self, branch, **kwargs): - """Cherry-pick a commit into a branch. - Args: - branch (str): Name of target branch. +class ProjectJobManager(RetrieveMixin, RESTManager): + _path = '/projects/%(project_id)s/jobs' + _obj_cls = ProjectJob + _from_parent_attrs = {'project_id': 'id'} - Raises: - GitlabCherryPickError: If the cherry pick could not be applied. - """ - url = ('/projects/%s/repository/commits/%s/cherry_pick' % - (self.project_id, self.id)) - r = self.gitlab._raw_post(url, data={'project_id': self.project_id, - 'branch': branch}, **kwargs) - errors = {400: GitlabCherryPickError} - raise_error_from_response(r, errors, expected_code=201) +class ProjectCommitStatus(RESTObject): + pass -class ProjectCommitManager(BaseManager): - obj_cls = ProjectCommit +class ProjectCommitStatusManager(RetrieveMixin, CreateMixin, RESTManager): + _path = ('/projects/%(project_id)s/repository/commits/%(commit_id)s' + '/statuses') + _obj_cls = ProjectCommitStatus + _from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'id'} + _create_attrs = (('state', ), + ('description', 'name', 'context', 'ref', 'target_url')) + def create(self, data, **kwargs): + """Create a new object. -class ProjectEnvironment(GitlabObject): - _url = '/projects/%(project_id)s/environments' - canGet = 'from_list' - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['name'] - optionalCreateAttrs = ['external_url'] - optionalUpdateAttrs = ['name', 'external_url'] + Args: + data (dict): Parameters to send to the server to create the + resource + **kwargs: Extra data to send to the Gitlab server (e.g. sudo or + 'ref_name', 'stage', 'name', 'all'. + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server cannot perform the request + Returns: + RESTObject: A new instance of the manage object class build with + the data sent by the server + """ + path = '/projects/%(project_id)s/statuses/%(commit_id)s' + computed_path = self._compute_path(path) + return CreateMixin.create(self, data, path=computed_path, **kwargs) -class ProjectEnvironmentManager(BaseManager): - obj_cls = ProjectEnvironment +class ProjectCommitComment(RESTObject): + pass -class ProjectKey(GitlabObject): - _url = '/projects/%(project_id)s/deploy_keys' - canUpdate = False - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['title', 'key'] +class ProjectCommitCommentManager(ListMixin, CreateMixin, RESTManager): + _path = ('/projects/%(project_id)s/repository/commits/%(commit_id)s' + '/comments') + _obj_cls = ProjectCommitComment + _from_parent_attrs = {'project_id': 'project_id', 'commit_id': 'id'} + _create_attrs = (('note', ), ('path', 'line', 'line_type')) -class ProjectKeyManager(BaseManager): - obj_cls = ProjectKey - def enable(self, key_id): - """Enable a deploy key for a project.""" - url = '/projects/%s/deploy_keys/%s/enable' % (self.parent.id, key_id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabProjectDeployKeyError, 201) +class ProjectCommit(RESTObject): + _short_print_attr = 'title' + _managers = ( + ('comments', 'ProjectCommitCommentManager'), + ('statuses', 'ProjectCommitStatusManager'), + ) + @exc.on_http_error(exc.GitlabGetError) + def diff(self, **kwargs): + """Generate the commit diff. -class ProjectEvent(GitlabObject): - _url = '/projects/%(project_id)s/events' - canGet = 'from_list' - canDelete = False - canUpdate = False - canCreate = False - requiredUrlAttrs = ['project_id'] - shortPrintAttr = 'target_title' + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + Raise: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the diff could not be retrieved -class ProjectEventManager(BaseManager): - obj_cls = ProjectEvent + Returns: + list: The changes done in this commit + """ + path = '%s/%s/diff' % (self.manager.path, self.get_id()) + return self.manager.gitlab.http_get(path, **kwargs) + @exc.on_http_error(exc.GitlabCherryPickError) + def cherry_pick(self, branch, **kwargs): + """Cherry-pick a commit into a branch. -class ProjectFork(GitlabObject): - _url = '/projects/%(project_id)s/fork' - canUpdate = False - canDelete = False - canList = False - canGet = False - requiredUrlAttrs = ['project_id'] - optionalCreateAttrs = ['namespace'] + Args: + branch (str): Name of target branch + **kwargs: Extra options to send to the server (e.g. sudo) + Raise: + GitlabAuthenticationError: If authentication is not correct + GitlabCherryPickError: If the cherry-pick could not be performed + """ + path = '%s/%s/cherry_pick' % (self.manager.path, self.get_id()) + post_data = {'branch': branch} + self.manager.gitlab.http_post(path, post_data=post_data, **kwargs) -class ProjectForkManager(BaseManager): - obj_cls = ProjectFork +class ProjectCommitManager(RetrieveMixin, CreateMixin, RESTManager): + _path = '/projects/%(project_id)s/repository/commits' + _obj_cls = ProjectCommit + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('branch', 'commit_message', 'actions'), + ('author_email', 'author_name')) -class ProjectHook(GitlabObject): - _url = '/projects/%(project_id)s/hooks' - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['url'] - optionalCreateAttrs = ['push_events', 'issues_events', 'note_events', - 'merge_requests_events', 'tag_push_events', - 'build_events', 'enable_ssl_verification', 'token', - 'pipeline_events', 'job_events', 'wiki_page_events'] - shortPrintAttr = 'url' +class ProjectEnvironment(SaveMixin, ObjectDeleteMixin, RESTObject): + pass -class ProjectHookManager(BaseManager): - obj_cls = ProjectHook +class ProjectEnvironmentManager(GetFromListMixin, CreateMixin, UpdateMixin, + DeleteMixin, RESTManager): + _path = '/projects/%(project_id)s/environments' + _obj_cls = ProjectEnvironment + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('name', ), ('external_url', )) + _update_attrs = (tuple(), ('name', 'external_url')) -class ProjectIssueNote(GitlabObject): - _url = '/projects/%(project_id)s/issues/%(issue_iid)s/notes' - _constructorTypes = {'author': 'User'} - canDelete = False - requiredUrlAttrs = ['project_id', 'issue_iid'] - requiredCreateAttrs = ['body'] - optionalCreateAttrs = ['created_at'] +class ProjectKey(ObjectDeleteMixin, RESTObject): + pass -class ProjectIssueNoteManager(BaseManager): - obj_cls = ProjectIssueNote +class ProjectKeyManager(NoUpdateMixin, RESTManager): + _path = '/projects/%(project_id)s/deploy_keys' + _obj_cls = ProjectKey + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('title', 'key'), tuple()) -class ProjectIssue(GitlabObject): - _url = '/projects/%(project_id)s/issues/' - _constructorTypes = {'author': 'User', 'assignee': 'User', - 'milestone': 'ProjectMilestone'} - optionalListAttrs = ['state', 'labels', 'milestone', 'order_by', 'sort'] - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['title'] - optionalCreateAttrs = ['description', 'assignee_id', 'milestone_id', - 'labels', 'created_at', 'due_date'] - optionalUpdateAttrs = ['title', 'description', 'assignee_id', - 'milestone_id', 'labels', 'created_at', - 'updated_at', 'state_event', 'due_date'] - shortPrintAttr = 'title' - idAttr = 'iid' - managers = ( - ('notes', 'ProjectIssueNoteManager', - [('project_id', 'project_id'), ('issue_iid', 'iid')]), - ) + @exc.on_http_error(exc.GitlabProjectDeployKeyError) + def enable(self, key_id, **kwargs): + """Enable a deploy key for a project. - def subscribe(self, **kwargs): - """Subscribe to an issue. + Args: + key_id (int): The ID of the key to enable + **kwargs: Extra options to send to the server (e.g. sudo) - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabSubscribeError: If the subscription cannot be done + Raise: + GitlabAuthenticationError: If authentication is not correct + GitlabProjectDeployKeyError: If the key could not be enabled """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/subscribe' % - {'project_id': self.project_id, 'issue_iid': self.iid}) + path = '%s/%s/enable' % (self.path, key_id) + self.gitlab.http_post(path, **kwargs) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabSubscribeError, [201, 304]) - self._set_from_dict(r.json()) - def unsubscribe(self, **kwargs): - """Unsubscribe an issue. +class ProjectEvent(RESTObject): + _short_print_attr = 'target_title' - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabUnsubscribeError: If the unsubscription cannot be done - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/unsubscribe' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabUnsubscribeError, [201, 304]) - self._set_from_dict(r.json()) +class ProjectEventManager(GetFromListMixin, RESTManager): + _path = '/projects/%(project_id)s/events' + _obj_cls = ProjectEvent + _from_parent_attrs = {'project_id': 'id'} - def move(self, to_project_id, **kwargs): - """Move the issue to another project. - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/move' % - {'project_id': self.project_id, 'issue_iid': self.iid}) +class ProjectFork(RESTObject): + pass - data = {'to_project_id': to_project_id} - data.update(**kwargs) - r = self.gitlab._raw_post(url, data=data) - raise_error_from_response(r, GitlabUpdateError, 201) - self._set_from_dict(r.json()) - def todo(self, **kwargs): - """Create a todo for the issue. +class ProjectForkManager(CreateMixin, RESTManager): + _path = '/projects/%(project_id)s/fork' + _obj_cls = ProjectFork + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (tuple(), ('namespace', )) - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/todo' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTodoError, [201, 304]) - def time_stats(self, **kwargs): - """Get time stats for the issue. +class ProjectHook(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'url' - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/time_stats' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return r.json() - def time_estimate(self, duration, **kwargs): - """Set an estimated time of work for the issue. +class ProjectHookManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/hooks' + _obj_cls = ProjectHook + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = ( + ('url', ), + ('push_events', 'issues_events', 'note_events', + 'merge_requests_events', 'tag_push_events', 'build_events', + 'enable_ssl_verification', 'token', 'pipeline_events') + ) + _update_attrs = ( + ('url', ), + ('push_events', 'issues_events', 'note_events', + 'merge_requests_events', 'tag_push_events', 'build_events', + 'enable_ssl_verification', 'token', 'pipeline_events') + ) - Args: - duration (str): duration in human format (e.g. 3h30) - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/time_estimate' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - data = {'duration': duration} - r = self.gitlab._raw_post(url, data, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() +class ProjectIssueNote(SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User'} - def reset_time_estimate(self, **kwargs): - """Resets estimated time for the issue to 0 seconds. - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/' - 'reset_time_estimate' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() +class ProjectIssueNoteManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/issues/%(issue_iid)s/notes' + _obj_cls = ProjectIssueNote + _from_parent_attrs = {'project_id': 'project_id', 'issue_iid': 'iid'} + _create_attrs = (('body', ), ('created_at')) + _update_attrs = (('body', ), tuple()) - def add_spent_time(self, duration, **kwargs): - """Set an estimated time of work for the issue. - Args: - duration (str): duration in human format (e.g. 3h30) +class ProjectIssue(SubscribableMixin, TodoMixin, TimeTrackingMixin, SaveMixin, + ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User', 'assignee': 'User', 'milestone': + 'ProjectMilestone'} + _short_print_attr = 'title' + _id_attr = 'iid' + _managers = (('notes', 'ProjectIssueNoteManager'), ) - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/' - 'add_spent_time' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - data = {'duration': duration} - r = self.gitlab._raw_post(url, data, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 201) - return r.json() + @exc.on_http_error(exc.GitlabUpdateError) + def move(self, to_project_id, **kwargs): + """Move the issue to another project. - def reset_spent_time(self, **kwargs): - """Set an estimated time of work for the issue. + Args: + to_project_id(int): ID of the target project + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. + GitlabAuthenticationError: If authentication is not correct + GitlabUpdateError: If the issue could not be moved """ - url = ('/projects/%(project_id)s/issues/%(issue_iid)s/' - 'reset_spent_time' % - {'project_id': self.project_id, 'issue_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() + path = '%s/%s/move' % (self.manager.path, self.get_id()) + data = {'to_project_id': to_project_id} + server_data = self.manager.gitlab.http_post(path, post_data=data, + **kwargs) + self._update_attrs(server_data) -class ProjectIssueManager(BaseManager): - obj_cls = ProjectIssue +class ProjectIssueManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/issues/' + _obj_cls = ProjectIssue + _from_parent_attrs = {'project_id': 'id'} + _list_filters = ('state', 'labels', 'milestone', 'order_by', 'sort') + _create_attrs = (('title', ), + ('description', 'assignee_id', 'milestone_id', 'labels', + 'created_at', 'due_date')) + _update_attrs = (tuple(), ('title', 'description', 'assignee_id', + 'milestone_id', 'labels', 'created_at', + 'updated_at', 'state_event', 'due_date')) -class ProjectMember(GitlabObject): - _url = '/projects/%(project_id)s/members' - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['access_level', 'user_id'] - optionalCreateAttrs = ['expires_at'] - requiredUpdateAttrs = ['access_level'] - optionalCreateAttrs = ['expires_at'] - shortPrintAttr = 'username' +class ProjectMember(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'username' -class ProjectMemberManager(BaseManager): - obj_cls = ProjectMember +class ProjectMemberManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/members' + _obj_cls = ProjectMember + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('access_level', 'user_id'), ('expires_at', )) + _update_attrs = (('access_level', ), ('expires_at', )) -class ProjectNote(GitlabObject): - _url = '/projects/%(project_id)s/notes' - _constructorTypes = {'author': 'User'} - canUpdate = False - canDelete = False - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['body'] +class ProjectNote(RESTObject): + _constructor_types = {'author': 'User'} -class ProjectNoteManager(BaseManager): - obj_cls = ProjectNote +class ProjectNoteManager(RetrieveMixin, RESTManager): + _path = '/projects/%(project_id)s/notes' + _obj_cls = ProjectNote + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('body', ), tuple()) class ProjectNotificationSettings(NotificationSettings): - _url = '/projects/%(project_id)s/notification_settings' - requiredUrlAttrs = ['project_id'] + pass -class ProjectNotificationSettingsManager(BaseManager): - obj_cls = ProjectNotificationSettings +class ProjectNotificationSettingsManager(NotificationSettingsManager): + _path = '/projects/%(project_id)s/notification_settings' + _obj_cls = ProjectNotificationSettings + _from_parent_attrs = {'project_id': 'id'} -class ProjectTagRelease(GitlabObject): - _url = '/projects/%(project_id)s/repository/tags/%(tag_name)/release' - canDelete = False - canList = False - requiredUrlAttrs = ['project_id', 'tag_name'] - requiredCreateAttrs = ['description'] - shortPrintAttr = 'description' +class ProjectTag(ObjectDeleteMixin, RESTObject): + _constructor_types = {'release': 'ProjectTagRelease', + 'commit': 'ProjectCommit'} + _id_attr = 'name' + _short_print_attr = 'name' - -class ProjectTag(GitlabObject): - _url = '/projects/%(project_id)s/repository/tags' - _constructorTypes = {'release': 'ProjectTagRelease', - 'commit': 'ProjectCommit'} - idAttr = 'name' - canGet = 'from_list' - canUpdate = False - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['tag_name', 'ref'] - optionalCreateAttrs = ['message'] - shortPrintAttr = 'name' - - def set_release_description(self, description): + def set_release_description(self, description, **kwargs): """Set the release notes on the tag. If the release doesn't exist yet, it will be created. If it already @@ -1076,172 +987,151 @@ class ProjectTag(GitlabObject): Args: description (str): Description of the release. + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabCreateError: If the server fails to create the release. - GitlabUpdateError: If the server fails to update the release. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server fails to create the release + GitlabUpdateError: If the server fails to update the release """ - url = '/projects/%s/repository/tags/%s/release' % (self.project_id, - self.name) + path = '%s/%s/release' % (self.manager.path, self.get_id()) + data = {'description': description} if self.release is None: - r = self.gitlab._raw_post(url, data={'description': description}) - raise_error_from_response(r, GitlabCreateError, 201) + try: + server_data = self.manager.gitlab.http_post(path, + post_data=data, + **kwargs) + except exc.GitlabHttpError as e: + raise exc.GitlabCreateError(e.response_code, e.error_message) else: - r = self.gitlab._raw_put(url, data={'description': description}) - raise_error_from_response(r, GitlabUpdateError, 200) - self.release = ProjectTagRelease(self, r.json()) + try: + server_data = self.manager.gitlab.http_put(path, + post_data=data, + **kwargs) + except exc.GitlabHttpError as e: + raise exc.GitlabUpdateError(e.response_code, e.error_message) + self.release = server_data -class ProjectTagManager(BaseManager): - obj_cls = ProjectTag +class ProjectTagManager(GetFromListMixin, CreateMixin, DeleteMixin, + RESTManager): + _path = '/projects/%(project_id)s/repository/tags' + _obj_cls = ProjectTag + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('tag_name', 'ref'), ('message',)) -class ProjectMergeRequestDiff(GitlabObject): - _url = ('/projects/%(project_id)s/merge_requests/' - '%(merge_request_iid)s/versions') - canCreate = False - canUpdate = False - canDelete = False - requiredUrlAttrs = ['project_id', 'merge_request_iid'] +class ProjectMergeRequestDiff(RESTObject): + pass -class ProjectMergeRequestDiffManager(BaseManager): - obj_cls = ProjectMergeRequestDiff +class ProjectMergeRequestDiffManager(RetrieveMixin, RESTManager): + _path = '/projects/%(project_id)s/merge_requests/%(mr_iid)s/versions' + _obj_cls = ProjectMergeRequestDiff + _from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'} -class ProjectMergeRequestNote(GitlabObject): - _url = ('/projects/%(project_id)s/merge_requests/%(merge_request_iid)s' - '/notes') - _constructorTypes = {'author': 'User'} - requiredUrlAttrs = ['project_id', 'merge_request_iid'] - requiredCreateAttrs = ['body'] +class ProjectMergeRequestNote(SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User'} -class ProjectMergeRequestNoteManager(BaseManager): - obj_cls = ProjectMergeRequestNote +class ProjectMergeRequestNoteManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/merge_requests/%(mr_iid)s/notes' + _obj_cls = ProjectMergeRequestNote + _from_parent_attrs = {'project_id': 'project_id', 'mr_iid': 'iid'} + _create_attrs = (('body', ), tuple()) + _update_attrs = (('body', ), tuple()) -class ProjectMergeRequest(GitlabObject): - _url = '/projects/%(project_id)s/merge_requests' - _constructorTypes = {'author': 'User', 'assignee': 'User'} - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['source_branch', 'target_branch', 'title'] - optionalCreateAttrs = ['assignee_id', 'description', 'target_project_id', - 'labels', 'milestone_id', 'remove_source_branch'] - optionalUpdateAttrs = ['target_branch', 'assignee_id', 'title', - 'description', 'state_event', 'labels', - 'milestone_id'] - optionalListAttrs = ['iids', 'state', 'order_by', 'sort'] - idAttr = 'iid' +class ProjectMergeRequest(SubscribableMixin, TodoMixin, TimeTrackingMixin, + SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'author': 'User', 'assignee': 'User'} + _id_attr = 'iid' - managers = ( - ('notes', 'ProjectMergeRequestNoteManager', - [('project_id', 'project_id'), ('merge_request_iid', 'iid')]), - ('diffs', 'ProjectMergeRequestDiffManager', - [('project_id', 'project_id'), ('merge_request_iid', 'iid')]), + _managers = ( + ('notes', 'ProjectMergeRequestNoteManager'), + ('diffs', 'ProjectMergeRequestDiffManager') ) - def _data_for_gitlab(self, extra_parameters={}, update=False, - as_json=True): - data = (super(ProjectMergeRequest, self) - ._data_for_gitlab(extra_parameters, update=update, - as_json=False)) - if update: - # Drop source_branch attribute as it is not accepted by the gitlab - # server (Issue #76) - data.pop('source_branch', None) - return json.dumps(data) - - def subscribe(self, **kwargs): - """Subscribe to a MR. - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabSubscribeError: If the subscription cannot be done - """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'subscribe' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabSubscribeError, [201, 304]) - if r.status_code == 201: - self._set_from_dict(r.json()) + @exc.on_http_error(exc.GitlabMROnBuildSuccessError) + def cancel_merge_when_pipeline_succeeds(self, **kwargs): + """Cancel merge when the pipeline succeeds. - def unsubscribe(self, **kwargs): - """Unsubscribe a MR. + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabUnsubscribeError: If the unsubscription cannot be done + GitlabAuthenticationError: If authentication is not correct + GitlabMROnBuildSuccessError: If the server could not handle the + request """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'unsubscribe' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabUnsubscribeError, [201, 304]) - if r.status_code == 200: - self._set_from_dict(r.json()) - - def cancel_merge_when_pipeline_succeeds(self, **kwargs): - """Cancel merge when build succeeds.""" - - u = ('/projects/%s/merge_requests/%s/' - 'cancel_merge_when_pipeline_succeeds' - % (self.project_id, self.iid)) - r = self.gitlab._raw_put(u, **kwargs) - errors = {401: GitlabMRForbiddenError, - 405: GitlabMRClosedError, - 406: GitlabMROnBuildSuccessError} - raise_error_from_response(r, errors) - return ProjectMergeRequest(self, r.json()) + path = ('%s/%s/cancel_merge_when_pipeline_succeeds' % + (self.manager.path, self.get_id())) + server_data = self.manager.gitlab.http_put(path, **kwargs) + self._update_attrs(server_data) + @exc.on_http_error(exc.GitlabListError) def closes_issues(self, **kwargs): - """List issues closed by the MR. + """List issues that will close on merge." - Returns: - list (ProjectIssue): List of closed issues + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. - """ - url = ('/projects/%s/merge_requests/%s/closes_issues' % - (self.project_id, self.iid)) - return self.gitlab._raw_list(url, ProjectIssue, **kwargs) + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the list could not be retrieved + Returns: + RESTObjectList: List of issues + """ + path = '%s/%s/closes_issues' % (self.manager.path, self.get_id()) + data_list = self.manager.gitlab.http_list(path, as_list=False, + **kwargs) + manager = ProjectIssueManager(self.manager.gitlab, + parent=self.manager._parent) + return RESTObjectList(manager, ProjectIssue, data_list) + + @exc.on_http_error(exc.GitlabListError) def commits(self, **kwargs): """List the merge request commits. - Returns: - list (ProjectCommit): List of commits + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabListError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the list could not be retrieved + + Returns: + RESTObjectList: The list of commits """ - url = ('/projects/%s/merge_requests/%s/commits' % - (self.project_id, self.iid)) - return self.gitlab._raw_list(url, ProjectCommit, **kwargs) + path = '%s/%s/commits' % (self.manager.path, self.get_id()) + data_list = self.manager.gitlab.http_list(path, as_list=False, + **kwargs) + manager = ProjectCommitManager(self.manager.gitlab, + parent=self.manager._parent) + return RESTObjectList(manager, ProjectCommit, data_list) + + @exc.on_http_error(exc.GitlabListError) def changes(self, **kwargs): """List the merge request changes. - Returns: - list (dict): List of changes + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabListError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the list could not be retrieved + + Returns: + RESTObjectList: List of changes """ - url = ('/projects/%s/merge_requests/%s/changes' % - (self.project_id, self.iid)) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabListError) - return r.json() + path = '%s/%s/changes' % (self.manager.path, self.get_id()) + return self.manager.gitlab.http_get(path, **kwargs) + @exc.on_http_error(exc.GitlabMRClosedError) def merge(self, merge_commit_message=None, should_remove_source_branch=False, merge_when_pipeline_succeeds=False, @@ -1254,17 +1144,13 @@ class ProjectMergeRequest(GitlabObject): branch merge_when_pipeline_succeeds (bool): Wait for the build to succeed, then merge + **kwargs: Extra options to send to the server (e.g. sudo) - Returns: - ProjectMergeRequest: The updated MR Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabMRForbiddenError: If the user doesn't have permission to - close thr MR - GitlabMRClosedError: If the MR is already closed + GitlabAuthenticationError: If authentication is not correct + GitlabMRClosedError: If the merge failed """ - url = '/projects/%s/merge_requests/%s/merge' % (self.project_id, - self.iid) + path = '%s/%s/merge' % (self.manager.path, self.get_id()) data = {} if merge_commit_message: data['merge_commit_message'] = merge_commit_message @@ -1273,205 +1159,253 @@ class ProjectMergeRequest(GitlabObject): if merge_when_pipeline_succeeds: data['merge_when_pipeline_succeeds'] = True - r = self.gitlab._raw_put(url, data=data, **kwargs) - errors = {401: GitlabMRForbiddenError, - 405: GitlabMRClosedError} - raise_error_from_response(r, errors) - self._set_from_dict(r.json()) + server_data = self.manager.gitlab.http_put(path, post_data=data, + **kwargs) + self._update_attrs(server_data) - def todo(self, **kwargs): - """Create a todo for the merge request. - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/todo' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTodoError, [201, 304]) +class ProjectMergeRequestManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/merge_requests' + _obj_cls = ProjectMergeRequest + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = ( + ('source_branch', 'target_branch', 'title'), + ('assignee_id', 'description', 'target_project_id', 'labels', + 'milestone_id', 'remove_source_branch') + ) + _update_attrs = (tuple(), ('target_branch', 'assignee_id', 'title', + 'description', 'state_event', 'labels', + 'milestone_id')) + _list_filters = ('iids', 'state', 'order_by', 'sort') - def time_stats(self, **kwargs): - """Get time stats for the merge request. - Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'time_stats' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return r.json() +class ProjectMilestone(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'title' - def time_estimate(self, duration, **kwargs): - """Set an estimated time of work for the merge request. + @exc.on_http_error(exc.GitlabListError) + def issues(self, **kwargs): + """List issues related to this milestone. Args: - duration (str): duration in human format (e.g. 3h30) + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'time_estimate' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - data = {'duration': duration} - r = self.gitlab._raw_post(url, data, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the list could not be retrieved - def reset_time_estimate(self, **kwargs): - """Resets estimated time for the merge request to 0 seconds. - - Raises: - GitlabConnectionError: If the server cannot be reached. + Returns: + RESTObjectList: The list of issues """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'reset_time_estimate' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() - def add_spent_time(self, duration, **kwargs): - """Set an estimated time of work for the merge request. + path = '%s/%s/issues' % (self.manager.path, self.get_id()) + data_list = self.manager.gitlab.http_list(path, as_list=False, + **kwargs) + manager = ProjectCommitManager(self.manager.gitlab, + parent=self.manager._parent) + # FIXME(gpocentek): the computed manager path is not correct + return RESTObjectList(manager, ProjectIssue, data_list) + + @exc.on_http_error(exc.GitlabListError) + def merge_requests(self, **kwargs): + """List the merge requests related to this milestone. Args: - duration (str): duration in human format (e.g. 3h30) + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'add_spent_time' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - data = {'duration': duration} - r = self.gitlab._raw_post(url, data, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 201) - return r.json() + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the list could not be retrieved - def reset_spent_time(self, **kwargs): - """Set an estimated time of work for the merge request. - - Raises: - GitlabConnectionError: If the server cannot be reached. + Returns: + RESTObjectList: The list of merge requests """ - url = ('/projects/%(project_id)s/merge_requests/%(mr_iid)s/' - 'reset_spent_time' % - {'project_id': self.project_id, 'mr_iid': self.iid}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabTimeTrackingError, 200) - return r.json() + path = '%s/%s/merge_requests' % (self.manager.path, self.get_id()) + data_list = self.manager.gitlab.http_list(path, as_list=False, + **kwargs) + manager = ProjectCommitManager(self.manager.gitlab, + parent=self.manager._parent) + # FIXME(gpocentek): the computed manager path is not correct + return RESTObjectList(manager, ProjectMergeRequest, data_list) -class ProjectMergeRequestManager(BaseManager): - obj_cls = ProjectMergeRequest +class ProjectMilestoneManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/milestones' + _obj_cls = ProjectMilestone + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('title', ), ('description', 'due_date', 'start_date', + 'state_event')) + _update_attrs = (tuple(), ('title', 'description', 'due_date', + 'start_date', 'state_event')) + _list_filters = ('iids', 'state') -class ProjectMilestone(GitlabObject): - _url = '/projects/%(project_id)s/milestones' - canDelete = False - requiredUrlAttrs = ['project_id'] - optionalListAttrs = ['iids', 'state'] - requiredCreateAttrs = ['title'] - optionalCreateAttrs = ['description', 'due_date', 'start_date', - 'state_event'] - optionalUpdateAttrs = requiredCreateAttrs + optionalCreateAttrs - shortPrintAttr = 'title' +class ProjectLabel(SubscribableMixin, SaveMixin, ObjectDeleteMixin, + RESTObject): + _id_attr = 'name' - def issues(self, **kwargs): - url = "/projects/%s/milestones/%s/issues" % (self.project_id, self.id) - return self.gitlab._raw_list(url, ProjectIssue, **kwargs) + # Update without ID, but we need an ID to get from list. + @exc.on_http_error(exc.GitlabUpdateError) + def save(self, **kwargs): + """Saves the changes made to the object to the server. - def merge_requests(self, **kwargs): - """List the merge requests related to this milestone + The object is updated to match what the server returns. - Returns: - list (ProjectMergeRequest): List of merge requests + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabListError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct. + GitlabUpdateError: If the server cannot perform the request. """ - url = ('/projects/%s/milestones/%s/merge_requests' % - (self.project_id, self.id)) - return self.gitlab._raw_list(url, ProjectMergeRequest, **kwargs) + updated_data = self._get_updated_data() + # call the manager + server_data = self.manager.update(None, updated_data, **kwargs) + self._update_attrs(server_data) -class ProjectMilestoneManager(BaseManager): - obj_cls = ProjectMilestone +class ProjectLabelManager(GetFromListMixin, CreateMixin, UpdateMixin, + DeleteMixin, RESTManager): + _path = '/projects/%(project_id)s/labels' + _obj_cls = ProjectLabel + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('name', 'color'), ('description', 'priority')) + _update_attrs = (('name', ), + ('new_name', 'color', 'description', 'priority')) -class ProjectLabel(GitlabObject): - _url = '/projects/%(project_id)s/labels' - _id_in_delete_url = False - _id_in_update_url = False - canGet = 'from_list' - requiredUrlAttrs = ['project_id'] - idAttr = 'name' - requiredDeleteAttrs = ['name'] - requiredCreateAttrs = ['name', 'color'] - optionalCreateAttrs = ['description', 'priority'] - requiredUpdateAttrs = ['name'] - optionalUpdateAttrs = ['new_name', 'color', 'description', 'priority'] + # Delete without ID. + @exc.on_http_error(exc.GitlabDeleteError) + def delete(self, name, **kwargs): + """Delete a Label on the server. - def subscribe(self, **kwargs): - """Subscribe to a label. + Args: + name: The name of the label + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabSubscribeError: If the subscription cannot be done + GitlabAuthenticationError: If authentication is not correct. + GitlabDeleteError: If the server cannot perform the request. + """ + self.gitlab.http_delete(self.path, query_data={'name': name}, **kwargs) + + +class ProjectFile(SaveMixin, ObjectDeleteMixin, RESTObject): + _id_attr = 'file_path' + _short_print_attr = 'file_path' + + def decode(self): + """Returns the decoded content of the file. + + Returns: + (str): the decoded content. + """ + return base64.b64decode(self.content) + + def save(self, branch, commit_message, **kwargs): + """Save the changes made to the file to the server. + + The object is updated to match what the server returns. + + Args: + branch (str): Branch in which the file will be updated + commit_message (str): Message to send with the commit + **kwargs: Extra options to send to the server (e.g. sudo) + + Raise: + GitlabAuthenticationError: If authentication is not correct + GitlabUpdateError: If the server cannot perform the request """ - url = ('/projects/%(project_id)s/labels/%(label_id)s/subscribe' % - {'project_id': self.project_id, 'label_id': self.name}) + self.branch = branch + self.commit_message = commit_message + super(ProjectFile, self).save(**kwargs) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabSubscribeError, [201, 304]) - self._set_from_dict(r.json()) + def delete(self, branch, commit_message, **kwargs): + """Delete the file from the server. - def unsubscribe(self, **kwargs): - """Unsubscribe a label. + Args: + branch (str): Branch from which the file will be removed + commit_message (str): Commit message for the deletion + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabUnsubscribeError: If the unsubscription cannot be done + GitlabAuthenticationError: If authentication is not correct + GitlabDeleteError: If the server cannot perform the request """ - url = ('/projects/%(project_id)s/labels/%(label_id)s/unsubscribe' % - {'project_id': self.project_id, 'label_id': self.name}) + self.manager.delete(self.get_id(), branch, commit_message, **kwargs) + + +class ProjectFileManager(GetMixin, CreateMixin, UpdateMixin, DeleteMixin, + RESTManager): + _path = '/projects/%(project_id)s/repository/files' + _obj_cls = ProjectFile + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('file_path', 'branch', 'content', 'commit_message'), + ('encoding', 'author_email', 'author_name')) + _update_attrs = (('file_path', 'branch', 'content', 'commit_message'), + ('encoding', 'author_email', 'author_name')) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabUnsubscribeError, [201, 304]) - self._set_from_dict(r.json()) + def get(self, file_path, ref, **kwargs): + """Retrieve a single file. + Args: + file_path (str): Path of the file to retrieve + ref (str): Name of the branch, tag or commit + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) -class ProjectLabelManager(BaseManager): - obj_cls = ProjectLabel + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the file could not be retrieved + Returns: + object: The generated RESTObject + """ + file_path = file_path.replace('/', '%2F') + return GetMixin.get(self, file_path, ref=ref, **kwargs) -class ProjectFile(GitlabObject): - _url = '/projects/%(project_id)s/repository/files' - canList = False - requiredUrlAttrs = ['project_id'] - requiredGetAttrs = ['ref'] - requiredCreateAttrs = ['file_path', 'branch', 'content', - 'commit_message'] - optionalCreateAttrs = ['encoding'] - requiredDeleteAttrs = ['branch', 'commit_message', 'file_path'] - shortPrintAttr = 'file_path' + @exc.on_http_error(exc.GitlabCreateError) + def create(self, data, **kwargs): + """Create a new object. - def decode(self): - """Returns the decoded content of the file. + Args: + data (dict): parameters to send to the server to create the + resource + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) Returns: - (str): the decoded content. + RESTObject: a new instance of the managed object class built with + the data sent by the server + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server cannot perform the request """ - return base64.b64decode(self.content) + self._check_missing_create_attrs(data) + file_path = data.pop('file_path') + path = '%s/%s' % (self.path, file_path) + server_data = self.gitlab.http_post(path, post_data=data, **kwargs) + return self._obj_cls(self, server_data) + + @exc.on_http_error(exc.GitlabDeleteError) + def delete(self, file_path, branch, commit_message, **kwargs): + """Delete a file on the server. -class ProjectFileManager(BaseManager): - obj_cls = ProjectFile + Args: + file_path (str): Path of the file to remove + branch (str): Branch from which the file will be removed + commit_message (str): Commit message for the deletion + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabDeleteError: If the server cannot perform the request + """ + path = '%s/%s' % (self.path, file_path.replace('/', '%2F')) + data = {'branch': branch, 'commit_message': commit_message} + self.gitlab.http_delete(path, query_data=data, **kwargs) - def raw(self, filepath, ref, streamed=False, action=None, chunk_size=1024, + @exc.on_http_error(exc.GitlabGetError) + def raw(self, file_path, ref, streamed=False, action=None, chunk_size=1024, **kwargs): """Return the content of a file for a commit. @@ -1480,165 +1414,172 @@ class ProjectFileManager(BaseManager): filepath (str): Path of the file to return streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for - treatment. + treatment action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the file could not be retrieved Returns: str: The file content - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. """ - url = ("/projects/%s/repository/files/%s/raw" % - (self.parent.id, filepath.replace('/', '%2F'))) - url += '?ref=%s' % ref - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) + file_path = file_path.replace('/', '%2F').replace('.', '%2E') + path = '%s/%s/raw' % (self.path, file_path) + query_data = {'ref': ref} + result = self.gitlab.http_get(path, query_data=query_data, + streamed=streamed, **kwargs) + return utils.response_content(result, streamed, action, chunk_size) -class ProjectPipeline(GitlabObject): - _url = '/projects/%(project_id)s/pipelines' - _create_url = '/projects/%(project_id)s/pipeline' +class ProjectPipeline(RESTObject): + @exc.on_http_error(exc.GitlabPipelineCancelError) + def cancel(self, **kwargs): + """Cancel the job. - canUpdate = False - canDelete = False + Args: + **kwargs: Extra options to send to the server (e.g. sudo) - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['ref'] + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabPipelineCancelError: If the request failed + """ + path = '%s/%s/cancel' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) + @exc.on_http_error(exc.GitlabPipelineRetryError) def retry(self, **kwargs): - """Retries failed builds in a pipeline. + """Retry the job. + + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabPipelineRetryError: If the retry cannot be done. + GitlabAuthenticationError: If authentication is not correct + GitlabPipelineRetryError: If the request failed """ - url = ('/projects/%(project_id)s/pipelines/%(id)s/retry' % - {'project_id': self.project_id, 'id': self.id}) - r = self.gitlab._raw_post(url, data=None, content_type=None, **kwargs) - raise_error_from_response(r, GitlabPipelineRetryError, 201) - self._set_from_dict(r.json()) + path = '%s/%s/retry' % (self.manager.path, self.get_id()) + self.manager.gitlab.http_post(path) - def cancel(self, **kwargs): - """Cancel builds in a pipeline. - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabPipelineCancelError: If the retry cannot be done. - """ - url = ('/projects/%(project_id)s/pipelines/%(id)s/cancel' % - {'project_id': self.project_id, 'id': self.id}) - r = self.gitlab._raw_post(url, data=None, content_type=None, **kwargs) - raise_error_from_response(r, GitlabPipelineRetryError, 200) - self._set_from_dict(r.json()) +class ProjectPipelineManager(RetrieveMixin, CreateMixin, RESTManager): + _path = '/projects/%(project_id)s/pipelines' + _obj_cls = ProjectPipeline + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('ref', ), tuple()) + def create(self, data, **kwargs): + """Creates a new object. -class ProjectPipelineManager(BaseManager): - obj_cls = ProjectPipeline + Args: + data (dict): Parameters to send to the server to create the + resource + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server cannot perform the request + + Returns: + RESTObject: A new instance of the managed object class build with + the data sent by the server + """ + path = self.path[:-1] # drop the 's' + return CreateMixin.create(self, data, path=path, **kwargs) -class ProjectSnippetNote(GitlabObject): - _url = '/projects/%(project_id)s/snippets/%(snippet_id)s/notes' - _constructorTypes = {'author': 'User'} - canUpdate = False - canDelete = False - requiredUrlAttrs = ['project_id', 'snippet_id'] - requiredCreateAttrs = ['body'] +class ProjectSnippetNote(RESTObject): + _constructor_types = {'author': 'User'} -class ProjectSnippetNoteManager(BaseManager): - obj_cls = ProjectSnippetNote +class ProjectSnippetNoteManager(RetrieveMixin, CreateMixin, RESTManager): + _path = '/projects/%(project_id)s/snippets/%(snippet_id)s/notes' + _obj_cls = ProjectSnippetNote + _from_parent_attrs = {'project_id': 'project_id', + 'snippet_id': 'id'} + _create_attrs = (('body', ), tuple()) -class ProjectSnippet(GitlabObject): +class ProjectSnippet(SaveMixin, ObjectDeleteMixin, RESTObject): _url = '/projects/%(project_id)s/snippets' - _constructorTypes = {'author': 'User'} - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['title', 'file_name', 'code'] - optionalCreateAttrs = ['lifetime', 'visibility'] - optionalUpdateAttrs = ['title', 'file_name', 'code', 'visibility'] - shortPrintAttr = 'title' - managers = ( - ('notes', 'ProjectSnippetNoteManager', - [('project_id', 'project_id'), ('snippet_id', 'id')]), - ) + _constructor_types = {'author': 'User'} + _short_print_attr = 'title' + _managers = (('notes', 'ProjectSnippetNoteManager'), ) + @exc.on_http_error(exc.GitlabGetError) def content(self, streamed=False, action=None, chunk_size=1024, **kwargs): - """Return the raw content of a snippet. + """Return the content of a snippet. Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for treatment. action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the content could not be retrieved Returns: str: The snippet content - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. """ - url = ("/projects/%(project_id)s/snippets/%(snippet_id)s/raw" % - {'project_id': self.project_id, 'snippet_id': self.id}) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) - + path = "%s/%s/raw" % (self.manager.path, self.get_id()) + result = self.manager.gitlab.http_get(path, streamed=streamed, + **kwargs) + return utils.response_content(result, streamed, action, chunk_size) -class ProjectSnippetManager(BaseManager): - obj_cls = ProjectSnippet +class ProjectSnippetManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/snippets' + _obj_cls = ProjectSnippet + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('title', 'file_name', 'code'), + ('lifetime', 'visibility')) + _update_attrs = (tuple(), ('title', 'file_name', 'code', 'visibility')) -class ProjectTrigger(GitlabObject): - _url = '/projects/%(project_id)s/triggers' - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['description'] - optionalUpdateAttrs = ['description'] +class ProjectTrigger(SaveMixin, ObjectDeleteMixin, RESTObject): def take_ownership(self, **kwargs): - """Update the owner of a trigger. + """Update the owner of a trigger.""" + path = '%s/%s/take_ownership' % (self.manager.path, self.get_id()) + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. - """ - url = ('/projects/%(project_id)s/triggers/%(id)s/take_ownership' % - {'project_id': self.project_id, 'id': self.id}) - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabUpdateError, 200) - self._set_from_dict(r.json()) + +class ProjectTriggerManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/triggers' + _obj_cls = ProjectTrigger + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('description', ), tuple()) + _update_attrs = (('description', ), tuple()) -class ProjectTriggerManager(BaseManager): - obj_cls = ProjectTrigger +class ProjectVariable(SaveMixin, ObjectDeleteMixin, RESTObject): + _id_attr = 'key' -class ProjectVariable(GitlabObject): - _url = '/projects/%(project_id)s/variables' - idAttr = 'key' - requiredUrlAttrs = ['project_id'] - requiredCreateAttrs = ['key', 'value'] +class ProjectVariableManager(CRUDMixin, RESTManager): + _path = '/projects/%(project_id)s/variables' + _obj_cls = ProjectVariable + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('key', 'value'), tuple()) + _update_attrs = (('key', 'value'), tuple()) -class ProjectVariableManager(BaseManager): - obj_cls = ProjectVariable +class ProjectService(SaveMixin, ObjectDeleteMixin, RESTObject): + pass -class ProjectService(GitlabObject): - _url = '/projects/%(project_id)s/services/%(service_name)s' - canList = False - canCreate = False - _id_in_update_url = False - _id_in_delete_url = False - getRequiresId = False - requiredUrlAttrs = ['project_id', 'service_name'] +class ProjectServiceManager(GetMixin, UpdateMixin, DeleteMixin, RESTManager): + _path = '/projects/%(project_id)s/services' + _from_parent_attrs = {'project_id': 'id'} + _obj_cls = ProjectService _service_attrs = { 'asana': (('api_key', ), ('restrict_to_branch', )), @@ -1664,16 +1605,10 @@ class ProjectService(GitlabObject): 'server')), 'irker': (('recipients', ), ('default_irc_uri', 'server_port', 'server_host', 'colorize_messages')), - 'jira': (tuple(), ( - # Required fields in GitLab >= 8.14 - 'url', 'project_key', - - # Required fields in GitLab < 8.14 - 'new_issue_url', 'project_url', 'issues_url', 'api_url', - 'description', - - # Optional fields - 'username', 'password', 'jira_issue_transition_id')), + 'jira': (('url', 'project_key'), + ('new_issue_url', 'project_url', 'issues_url', 'api_url', + 'description', 'username', 'password', + 'jira_issue_transition_id')), 'pivotaltracker': (('token', ), tuple()), 'pushover': (('api_key', 'user_key', 'priority'), ('device', 'sound')), 'redmine': (('new_issue_url', 'project_url', 'issues_url'), @@ -1683,33 +1618,44 @@ class ProjectService(GitlabObject): tuple()) } - def _data_for_gitlab(self, extra_parameters={}, update=False, - as_json=True): - data = (super(ProjectService, self) - ._data_for_gitlab(extra_parameters, update=update, - as_json=False)) - missing = [] - # Mandatory args - for attr in self._service_attrs[self.service_name][0]: - if not hasattr(self, attr): - missing.append(attr) - else: - data[attr] = getattr(self, attr) + def get(self, id, **kwargs): + """Retrieve a single object. + + Args: + id (int or str): ID of the object to retrieve + lazy (bool): If True, don't request the server, but create a + shallow object giving access to the managers. This is + useful if you want to avoid useless calls to the API. + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) + + Returns: + object: The generated RESTObject. - if missing: - raise GitlabUpdateError('Missing attribute(s): %s' % - ", ".join(missing)) + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server cannot perform the request + """ + obj = super(ProjectServiceManager, self).get(id, **kwargs) + obj.id = id + return obj - # Optional args - for attr in self._service_attrs[self.service_name][1]: - if hasattr(self, attr): - data[attr] = getattr(self, attr) + def update(self, id=None, new_data={}, **kwargs): + """Update an object on the server. - return json.dumps(data) + Args: + id: ID of the object to update (can be None if not required) + new_data: the update data for the object + **kwargs: Extra options to send to the Gitlab server (e.g. sudo) + Returns: + dict: The new object data (*not* a RESTObject) -class ProjectServiceManager(BaseManager): - obj_cls = ProjectService + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabUpdateError: If the server cannot perform the request + """ + super(ProjectServiceManager, self).update(id, new_data, **kwargs) + self.id = id def available(self, **kwargs): """List the services known by python-gitlab. @@ -1717,332 +1663,321 @@ class ProjectServiceManager(BaseManager): Returns: list (str): The list of service code names. """ - return list(ProjectService._service_attrs.keys()) - - -class ProjectAccessRequest(GitlabObject): - _url = '/projects/%(project_id)s/access_requests' - canGet = 'from_list' - canUpdate = False - - def approve(self, access_level=gitlab.DEVELOPER_ACCESS, **kwargs): - """Approve an access request. - - Attrs: - access_level (int): The access level for the user. - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabUpdateError: If the server fails to perform the request. - """ - - url = ('/projects/%(project_id)s/access_requests/%(id)s/approve' % - {'project_id': self.project_id, 'id': self.id}) - data = {'access_level': access_level} - r = self.gitlab._raw_put(url, data=data, **kwargs) - raise_error_from_response(r, GitlabUpdateError, 201) - self._set_from_dict(r.json()) - - -class ProjectAccessRequestManager(BaseManager): - obj_cls = ProjectAccessRequest - - -class ProjectDeployment(GitlabObject): - _url = '/projects/%(project_id)s/deployments' - canCreate = False - canUpdate = False - canDelete = False - - -class ProjectDeploymentManager(BaseManager): - obj_cls = ProjectDeployment - - -class ProjectRunner(GitlabObject): - _url = '/projects/%(project_id)s/runners' - canUpdate = False - requiredCreateAttrs = ['runner_id'] - - -class ProjectRunnerManager(BaseManager): - obj_cls = ProjectRunner - - -class Project(GitlabObject): - _url = '/projects' - _constructorTypes = {'owner': 'User', 'namespace': 'Group'} - optionalListAttrs = ['search'] - requiredCreateAttrs = ['name'] - optionalListAttrs = ['search', 'owned', 'starred', 'archived', - 'visibility', 'order_by', 'sort', 'simple', - 'membership', 'statistics'] - optionalCreateAttrs = ['path', 'namespace_id', 'description', - 'issues_enabled', 'merge_requests_enabled', - 'builds_enabled', 'wiki_enabled', - 'snippets_enabled', 'container_registry_enabled', - 'shared_runners_enabled', 'visibility', - 'import_url', 'public_builds', - 'only_allow_merge_if_build_succeeds', - 'only_allow_merge_if_all_discussions_are_resolved', - 'lfs_enabled', 'request_access_enabled'] - optionalUpdateAttrs = ['name', 'path', 'default_branch', 'description', - 'issues_enabled', 'merge_requests_enabled', - 'builds_enabled', 'wiki_enabled', - 'snippets_enabled', 'container_registry_enabled', - 'shared_runners_enabled', 'visibility', - 'import_url', 'public_builds', - 'only_allow_merge_if_build_succeeds', - 'only_allow_merge_if_all_discussions_are_resolved', - 'lfs_enabled', 'request_access_enabled'] - shortPrintAttr = 'path' - managers = ( - ('accessrequests', 'ProjectAccessRequestManager', - [('project_id', 'id')]), - ('boards', 'ProjectBoardManager', [('project_id', 'id')]), - ('board_lists', 'ProjectBoardListManager', [('project_id', 'id')]), - ('branches', 'ProjectBranchManager', [('project_id', 'id')]), - ('jobs', 'ProjectJobManager', [('project_id', 'id')]), - ('commits', 'ProjectCommitManager', [('project_id', 'id')]), - ('deployments', 'ProjectDeploymentManager', [('project_id', 'id')]), - ('environments', 'ProjectEnvironmentManager', [('project_id', 'id')]), - ('events', 'ProjectEventManager', [('project_id', 'id')]), - ('files', 'ProjectFileManager', [('project_id', 'id')]), - ('forks', 'ProjectForkManager', [('project_id', 'id')]), - ('hooks', 'ProjectHookManager', [('project_id', 'id')]), - ('keys', 'ProjectKeyManager', [('project_id', 'id')]), - ('issues', 'ProjectIssueManager', [('project_id', 'id')]), - ('labels', 'ProjectLabelManager', [('project_id', 'id')]), - ('members', 'ProjectMemberManager', [('project_id', 'id')]), - ('mergerequests', 'ProjectMergeRequestManager', - [('project_id', 'id')]), - ('milestones', 'ProjectMilestoneManager', [('project_id', 'id')]), - ('notes', 'ProjectNoteManager', [('project_id', 'id')]), - ('notificationsettings', 'ProjectNotificationSettingsManager', - [('project_id', 'id')]), - ('pipelines', 'ProjectPipelineManager', [('project_id', 'id')]), - ('runners', 'ProjectRunnerManager', [('project_id', 'id')]), - ('services', 'ProjectServiceManager', [('project_id', 'id')]), - ('snippets', 'ProjectSnippetManager', [('project_id', 'id')]), - ('tags', 'ProjectTagManager', [('project_id', 'id')]), - ('triggers', 'ProjectTriggerManager', [('project_id', 'id')]), - ('variables', 'ProjectVariableManager', [('project_id', 'id')]), + return list(self._service_attrs.keys()) + + +class ProjectAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject): + pass + + +class ProjectAccessRequestManager(GetFromListMixin, CreateMixin, DeleteMixin, + RESTManager): + _path = '/projects/%(project_id)s/access_requests' + _obj_cls = ProjectAccessRequest + _from_parent_attrs = {'project_id': 'id'} + + +class ProjectDeployment(RESTObject): + pass + + +class ProjectDeploymentManager(RetrieveMixin, RESTManager): + _path = '/projects/%(project_id)s/deployments' + _obj_cls = ProjectDeployment + _from_parent_attrs = {'project_id': 'id'} + + +class ProjectRunner(ObjectDeleteMixin, RESTObject): + pass + + +class ProjectRunnerManager(NoUpdateMixin, RESTManager): + _path = '/projects/%(project_id)s/runners' + _obj_cls = ProjectRunner + _from_parent_attrs = {'project_id': 'id'} + _create_attrs = (('runner_id', ), tuple()) + + +class Project(SaveMixin, ObjectDeleteMixin, RESTObject): + _constructor_types = {'owner': 'User', 'namespace': 'Group'} + _short_print_attr = 'path' + _managers = ( + ('accessrequests', 'ProjectAccessRequestManager'), + ('boards', 'ProjectBoardManager'), + ('branches', 'ProjectBranchManager'), + ('jobs', 'ProjectJobManager'), + ('commits', 'ProjectCommitManager'), + ('deployments', 'ProjectDeploymentManager'), + ('environments', 'ProjectEnvironmentManager'), + ('events', 'ProjectEventManager'), + ('files', 'ProjectFileManager'), + ('forks', 'ProjectForkManager'), + ('hooks', 'ProjectHookManager'), + ('keys', 'ProjectKeyManager'), + ('issues', 'ProjectIssueManager'), + ('labels', 'ProjectLabelManager'), + ('members', 'ProjectMemberManager'), + ('mergerequests', 'ProjectMergeRequestManager'), + ('milestones', 'ProjectMilestoneManager'), + ('notes', 'ProjectNoteManager'), + ('notificationsettings', 'ProjectNotificationSettingsManager'), + ('pipelines', 'ProjectPipelineManager'), + ('runners', 'ProjectRunnerManager'), + ('services', 'ProjectServiceManager'), + ('snippets', 'ProjectSnippetManager'), + ('tags', 'ProjectTagManager'), + ('triggers', 'ProjectTriggerManager'), + ('variables', 'ProjectVariableManager'), ) + @exc.on_http_error(exc.GitlabGetError) def repository_tree(self, path='', ref='', **kwargs): """Return a list of files in the repository. Args: path (str): Path of the top folder (/ by default) ref (str): Reference to a commit or branch - - Returns: - str: The json representation of the tree. + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server failed to perform the request + + Returns: + list: The representation of the tree """ - url = "/projects/%s/repository/tree" % (self.id) - params = [] + gl_path = '/projects/%s/repository/tree' % self.get_id() + query_data = {} if path: - params.append(urllib.parse.urlencode({'path': path})) + query_data['path'] = path if ref: - params.append("ref=%s" % ref) - if params: - url += '?' + "&".join(params) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return r.json() + query_data['ref'] = ref + return self.manager.gitlab.http_get(gl_path, query_data=query_data, + **kwargs) + + @exc.on_http_error(exc.GitlabGetError) + def repository_blob(self, sha, **kwargs): + """Return a blob by blob SHA. + + Args: + sha(str): ID of the blob + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server failed to perform the request + + Returns: + str: The blob metadata + """ + + path = '/projects/%s/repository/blobs/%s' % (self.get_id(), sha) + return self.manager.gitlab.http_get(path, **kwargs) + @exc.on_http_error(exc.GitlabGetError) def repository_raw_blob(self, sha, streamed=False, action=None, chunk_size=1024, **kwargs): - """Returns the raw file contents for a blob by blob SHA. + """Return the raw file contents for a blob. Args: sha(str): ID of the blob streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for - treatment. + treatment action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. - - Returns: - str: The blob content + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server failed to perform the request + + Returns: + str: The blob content if streamed is False, None otherwise """ - url = "/projects/%s/repository/raw_blobs/%s" % (self.id, sha) - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) + path = '/projects/%s/repository/blobs/%s/raw' % (self.get_id(), sha) + result = self.manager.gitlab.http_get(path, streamed=streamed, + **kwargs) + return utils.response_content(result, streamed, action, chunk_size) + @exc.on_http_error(exc.GitlabGetError) def repository_compare(self, from_, to, **kwargs): - """Returns a diff between two branches/commits. + """Return a diff between two branches/commits. Args: - from_(str): orig branch/SHA - to(str): dest branch/SHA + from_(str): Source branch/SHA + to(str): Destination branch/SHA + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server failed to perform the request Returns: str: The diff - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. """ - url = "/projects/%s/repository/compare" % self.id - url = "%s?from=%s&to=%s" % (url, from_, to) - r = self.gitlab._raw_get(url, **kwargs) - raise_error_from_response(r, GitlabGetError) - return r.json() + path = '/projects/%s/repository/compare' % self.get_id() + query_data = {'from': from_, 'to': to} + return self.manager.gitlab.http_get(path, query_data=query_data, + **kwargs) - def repository_contributors(self): - """Returns a list of contributors for the project. + @exc.on_http_error(exc.GitlabGetError) + def repository_contributors(self, **kwargs): + """Return a list of contributors for the project. - Returns: - list: The contibutors + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabGetError: If the server failed to perform the request + + Returns: + list: The contributors """ - url = "/projects/%s/repository/contributors" % self.id - r = self.gitlab._raw_get(url) - raise_error_from_response(r, GitlabListError) - return r.json() + path = '/projects/%s/repository/contributors' % self.get_id() + return self.manager.gitlab.http_get(path, **kwargs) + @exc.on_http_error(exc.GitlabListError) def repository_archive(self, sha=None, streamed=False, action=None, chunk_size=1024, **kwargs): """Return a tarball of the repository. Args: - sha (str): ID of the commit (default branch by default). + sha (str): ID of the commit (default branch by default) streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for - treatment. + treatment action (callable): Callable responsible of dealing with chunk of - data. - chunk_size (int): Size of each chunk. - - Returns: - str: The binary data of the archive. + data + chunk_size (int): Size of each chunk + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabGetError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the server failed to perform the request + + Returns: + str: The binary data of the archive """ - url = '/projects/%s/repository/archive' % self.id + path = '/projects/%s/repository/archive' % self.get_id() + query_data = {} if sha: - url += '?sha=%s' % sha - r = self.gitlab._raw_get(url, streamed=streamed, **kwargs) - raise_error_from_response(r, GitlabGetError) - return utils.response_content(r, streamed, action, chunk_size) + query_data['sha'] = sha + result = self.manager.gitlab.http_get(path, query_data=query_data, + streamed=streamed, **kwargs) + return utils.response_content(result, streamed, action, chunk_size) - def create_fork_relation(self, forked_from_id): + @exc.on_http_error(exc.GitlabCreateError) + def create_fork_relation(self, forked_from_id, **kwargs): """Create a forked from/to relation between existing projects. Args: forked_from_id (int): The ID of the project that was forked from + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabCreateError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the relation could not be created """ - url = "/projects/%s/fork/%s" % (self.id, forked_from_id) - r = self.gitlab._raw_post(url) - raise_error_from_response(r, GitlabCreateError, 201) + path = '/projects/%s/fork/%s' % (self.get_id(), forked_from_id) + self.manager.gitlab.http_post(path, **kwargs) - def delete_fork_relation(self): + @exc.on_http_error(exc.GitlabDeleteError) + def delete_fork_relation(self, **kwargs): """Delete a forked relation between existing projects. + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabDeleteError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabDeleteError: If the server failed to perform the request """ - url = "/projects/%s/fork" % self.id - r = self.gitlab._raw_delete(url) - raise_error_from_response(r, GitlabDeleteError) + path = '/projects/%s/fork' % self.get_id() + self.manager.gitlab.http_delete(path, **kwargs) + @exc.on_http_error(exc.GitlabCreateError) def star(self, **kwargs): """Star a project. - Returns: - Project: the updated Project + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabCreateError: If the action cannot be done - GitlabConnectionError: If the server cannot be reached. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server failed to perform the request """ - url = "/projects/%s/star" % self.id - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabCreateError, [201, 304]) - return Project(self.gitlab, r.json()) if r.status_code == 201 else self + path = '/projects/%s/star' % self.get_id() + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) + @exc.on_http_error(exc.GitlabDeleteError) def unstar(self, **kwargs): """Unstar a project. - Returns: - Project: the updated Project + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabDeleteError: If the action cannot be done - GitlabConnectionError: If the server cannot be reached. + GitlabAuthenticationError: If authentication is not correct + GitlabDeleteError: If the server failed to perform the request """ - url = "/projects/%s/unstar" % self.id - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabDeleteError, [201, 304]) - return Project(self.gitlab, r.json()) if r.status_code == 201 else self + path = '/projects/%s/unstar' % self.get_id() + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) + @exc.on_http_error(exc.GitlabCreateError) def archive(self, **kwargs): """Archive a project. - Returns: - Project: the updated Project + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabCreateError: If the action cannot be done - GitlabConnectionError: If the server cannot be reached. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server failed to perform the request """ - url = "/projects/%s/archive" % self.id - r = self.gitlab._raw_post(url, **kwargs) - raise_error_from_response(r, GitlabCreateError, 201) - return Project(self.gitlab, r.json()) if r.status_code == 201 else self + path = '/projects/%s/archive' % self.get_id() + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) + @exc.on_http_error(exc.GitlabDeleteError) def unarchive(self, **kwargs): """Unarchive a project. - Returns: - Project: the updated Project + Args: + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabDeleteError: If the action cannot be done - GitlabConnectionError: If the server cannot be reached. + GitlabAuthenticationError: If authentication is not correct + GitlabDeleteError: If the server failed to perform the request """ - url = "/projects/%s/unarchive" % self.id - r = self.gitlab._raw_delete(url, **kwargs) - raise_error_from_response(r, GitlabCreateError, 201) - return Project(self.gitlab, r.json()) if r.status_code == 201 else self + path = '/projects/%s/unarchive' % self.get_id() + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) - def share(self, group_id, group_access, **kwargs): + @exc.on_http_error(exc.GitlabCreateError) + def share(self, group_id, group_access, expires_at=None, **kwargs): """Share the project with a group. Args: group_id (int): ID of the group. group_access (int): Access level for the group. + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabCreateError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server failed to perform the request """ - url = "/projects/%s/share" % self.id - data = {'group_id': group_id, 'group_access': group_access} - r = self.gitlab._raw_post(url, data=data, **kwargs) - raise_error_from_response(r, GitlabCreateError, 201) + path = '/projects/%s/share' % self.get_id() + data = {'group_id': group_id, + 'group_access': group_access, + 'expires_at': expires_at} + self.manager.gitlab.http_post(path, post_data=data, **kwargs) + @exc.on_http_error(exc.GitlabCreateError) def trigger_pipeline(self, ref, token, variables={}, **kwargs): """Trigger a CI build. @@ -2052,129 +1987,176 @@ class Project(GitlabObject): ref (str): Commit to build; can be a commit SHA, a branch name, ... token (str): The trigger token variables (dict): Variables passed to the build script + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabCreateError: If the server fails to perform the request. + GitlabAuthenticationError: If authentication is not correct + GitlabCreateError: If the server failed to perform the request """ - url = "/projects/%s/trigger/pipeline" % self.id + path = '/projects/%s/trigger/pipeline' % self.get_id() form = {r'variables[%s]' % k: v for k, v in six.iteritems(variables)} - data = {'ref': ref, 'token': token} - data.update(form) - r = self.gitlab._raw_post(url, data=data, **kwargs) - raise_error_from_response(r, GitlabCreateError, 201) + post_data = {'ref': ref, 'token': token} + post_data.update(form) + self.manager.gitlab.http_post(path, post_data=post_data, **kwargs) -class Runner(GitlabObject): - _url = '/runners' - canCreate = False - optionalUpdateAttrs = ['description', 'active', 'tag_list'] - optionalListAttrs = ['scope'] +class Runner(SaveMixin, ObjectDeleteMixin, RESTObject): + pass -class RunnerManager(BaseManager): - obj_cls = Runner +class RunnerManager(RetrieveMixin, UpdateMixin, DeleteMixin, RESTManager): + _path = '/runners' + _obj_cls = Runner + _update_attrs = (tuple(), ('description', 'active', 'tag_list')) + _list_filters = ('scope', ) + @exc.on_http_error(exc.GitlabListError) def all(self, scope=None, **kwargs): """List all the runners. Args: scope (str): The scope of runners to show, one of: specific, shared, active, paused, online + all (bool): If True, return all the items, without pagination + per_page (int): Number of items to retrieve per request + page (int): ID of the page to return (starts with page 1) + as_list (bool): If set to False and no pagination option is + defined, return a generator instead of a list + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabListError: If the server failed to perform the request Returns: list(Runner): a list of runners matching the scope. - - Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabListError: If the resource cannot be found """ - url = '/runners/all' + path = '/runners/all' + query_data = {} if scope is not None: - url += '?scope=' + scope - return self.gitlab._raw_list(url, self.obj_cls, **kwargs) + query_data['scope'] = scope + return self.gitlab.http_list(path, query_data, **kwargs) + +class Todo(ObjectDeleteMixin, RESTObject): + @exc.on_http_error(exc.GitlabTodoError) + def mark_as_done(self, **kwargs): + """Mark the todo as done. -class Todo(GitlabObject): - _url = '/todos' - canGet = 'from_list' - canUpdate = False - canCreate = False - optionalListAttrs = ['action', 'author_id', 'project_id', 'state', 'type'] + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + + Raises: + GitlabAuthenticationError: If authentication is not correct + GitlabTodoError: If the server failed to perform the request + """ + path = '%s/%s/mark_as_done' % (self.manager.path, self.id) + server_data = self.manager.gitlab.http_post(path, **kwargs) + self._update_attrs(server_data) -class TodoManager(BaseManager): - obj_cls = Todo +class TodoManager(GetFromListMixin, DeleteMixin, RESTManager): + _path = '/todos' + _obj_cls = Todo + _list_filters = ('action', 'author_id', 'project_id', 'state', 'type') - def delete_all(self, **kwargs): + @exc.on_http_error(exc.GitlabTodoError) + def mark_all_as_done(self, **kwargs): """Mark all the todos as done. + Args: + **kwargs: Extra options to send to the server (e.g. sudo) + Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabDeleteError: If the resource cannot be found + GitlabAuthenticationError: If authentication is not correct + GitlabTodoError: If the server failed to perform the request Returns: - The number of todos maked done. + int: The number of todos maked done """ - url = '/todos' - r = self.gitlab._raw_delete(url, **kwargs) - raise_error_from_response(r, GitlabDeleteError) - return int(r.text) + result = self.gitlab.http_post('/todos/mark_as_done', **kwargs) + try: + return int(result) + except ValueError: + return 0 + + +class ProjectManager(CRUDMixin, RESTManager): + _path = '/projects' + _obj_cls = Project + _create_attrs = ( + ('name', ), + ('path', 'namespace_id', 'description', 'issues_enabled', + 'merge_requests_enabled', 'builds_enabled', 'wiki_enabled', + 'snippets_enabled', 'container_registry_enabled', + 'shared_runners_enabled', 'visibility', 'import_url', 'public_builds', + 'only_allow_merge_if_build_succeeds', + 'only_allow_merge_if_all_discussions_are_resolved', 'lfs_enabled', + 'request_access_enabled') + ) + _update_attrs = ( + tuple(), + ('name', 'path', 'default_branch', 'description', 'issues_enabled', + 'merge_requests_enabled', 'builds_enabled', 'wiki_enabled', + 'snippets_enabled', 'container_registry_enabled', + 'shared_runners_enabled', 'visibility', 'import_url', 'public_builds', + 'only_allow_merge_if_build_succeeds', + 'only_allow_merge_if_all_discussions_are_resolved', 'lfs_enabled', + 'request_access_enabled') + ) + _list_filters = ('search', 'owned', 'starred', 'archived', 'visibility', + 'order_by', 'sort', 'simple', 'membership', 'statistics', + 'with_issues_enabled', 'with_merge_requests_enabled') + +class GroupProject(Project): + pass -class ProjectManager(BaseManager): - obj_cls = Project +class GroupProjectManager(GetFromListMixin, RESTManager): + _path = '/groups/%(group_id)s/projects' + _obj_cls = GroupProject + _from_parent_attrs = {'group_id': 'id'} + _list_filters = ('archived', 'visibility', 'order_by', 'sort', 'search', + 'ci_enabled_first') -class GroupProject(Project): - _url = '/groups/%(group_id)s/projects' - canGet = 'from_list' - canCreate = False - canDelete = False - canUpdate = False - optionalListAttrs = ['archived', 'visibility', 'order_by', 'sort', - 'search', 'ci_enabled_first'] - - def __init__(self, *args, **kwargs): - Project.__init__(self, *args, **kwargs) - - -class GroupProjectManager(ProjectManager): - obj_cls = GroupProject - - -class Group(GitlabObject): - _url = '/groups' - requiredCreateAttrs = ['name', 'path'] - optionalCreateAttrs = ['description', 'visibility', 'parent_id', - 'lfs_enabled', 'request_access_enabled'] - optionalUpdateAttrs = ['name', 'path', 'description', 'visibility', - 'lfs_enabled', 'request_access_enabled'] - shortPrintAttr = 'name' - managers = ( - ('accessrequests', 'GroupAccessRequestManager', [('group_id', 'id')]), - ('members', 'GroupMemberManager', [('group_id', 'id')]), - ('notificationsettings', 'GroupNotificationSettingsManager', - [('group_id', 'id')]), - ('projects', 'GroupProjectManager', [('group_id', 'id')]), - ('issues', 'GroupIssueManager', [('group_id', 'id')]), + +class Group(SaveMixin, ObjectDeleteMixin, RESTObject): + _short_print_attr = 'name' + _managers = ( + ('accessrequests', 'GroupAccessRequestManager'), + ('members', 'GroupMemberManager'), + ('notificationsettings', 'GroupNotificationSettingsManager'), + ('projects', 'GroupProjectManager'), + ('issues', 'GroupIssueManager'), ) + @exc.on_http_error(exc.GitlabTransferProjectError) def transfer_project(self, id, **kwargs): - """Transfers a project to this new groups. + """Transfer a project to this group. - Attrs: - id (int): ID of the project to transfer. + Args: + id (int): ID of the project to transfer + **kwargs: Extra options to send to the server (e.g. sudo) Raises: - GitlabConnectionError: If the server cannot be reached. - GitlabTransferProjectError: If the server fails to perform the - request. + GitlabAuthenticationError: If authentication is not correct + GitlabTransferProjectError: If the project could not be transfered """ - url = '/groups/%d/projects/%d' % (self.id, id) - r = self.gitlab._raw_post(url, None, **kwargs) - raise_error_from_response(r, GitlabTransferProjectError, 201) + path = '/groups/%d/projects/%d' % (self.id, id) + self.manager.gitlab.http_post(path, **kwargs) -class GroupManager(BaseManager): - obj_cls = Group +class GroupManager(CRUDMixin, RESTManager): + _path = '/groups' + _obj_cls = Group + _create_attrs = ( + ('name', 'path'), + ('description', 'visibility', 'parent_id', 'lfs_enabled', + 'request_access_enabled') + ) + _update_attrs = ( + tuple(), + ('name', 'path', 'description', 'visibility', 'lfs_enabled', + 'request_access_enabled') + ) |
