summaryrefslogtreecommitdiff
path: root/gitlab/mixins.py
blob: 761227630ac0283e7d416def9548d49c4b93b16c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 Gauvain Pocentek <gauvain@pocentek.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from gitlab import base


class GetMixin(object):
    def get(self, id, **kwargs):
        """Retrieve a single object.

        Args:
            id (int or str): ID of the object to retrieve
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo)

        Returns:
            object: The generated RESTObject.

        Raises:
            GitlabGetError: If the server cannot perform the request.
        """
        path = '%s/%s' % (self._path, id)
        server_data = self.gitlab.http_get(path, **kwargs)
        return self._obj_cls(self, server_data)


class GetWithoutIdMixin(object):
    def get(self, **kwargs):
        """Retrieve a single object.

        Args:
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo)

        Returns:
            object: The generated RESTObject.

        Raises:
            GitlabGetError: If the server cannot perform the request.
        """
        server_data = self.gitlab.http_get(self._path, **kwargs)
        return self._obj_cls(self, server_data)


class ListMixin(object):
    def list(self, **kwargs):
        """Retrieves a list of objects.

        Args:
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo).
                      If ``all`` is passed and set to True, the entire list of
                      objects will be returned.

        Returns:
            RESTObjectList: Generator going through the list of objects, making
                            queries to the server when required.
                            If ``all=True`` is passed as argument, returns
                            list(RESTObjectList).
        """

        obj = self.gitlab.http_list(self._path, **kwargs)
        if isinstance(obj, list):
            return [self._obj_cls(self, item) for item in obj]
        else:
            return base.RESTObjectList(self, self._obj_cls, obj)


class GetFromListMixin(ListMixin):
    def get(self, id, **kwargs):
        """Retrieve a single object.

        Args:
            id (int or str): ID of the object to retrieve
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo)

        Returns:
            object: The generated RESTObject.

        Raises:
            GitlabGetError: If the server cannot perform the request.
        """
        gen = self.list()
        for obj in gen:
            if str(obj.get_id()) == str(id):
                return obj


class RetrieveMixin(ListMixin, GetMixin):
    pass


class CreateMixin(object):
    def _check_missing_attrs(self, data):
        required, optional = self.get_create_attrs()
        missing = []
        for attr in required:
            if attr not in data:
                missing.append(attr)
                continue
        if missing:
            raise AttributeError("Missing attributes: %s" % ", ".join(missing))

    def get_create_attrs(self):
        """Returns the required and optional arguments.

        Returns:
            tuple: 2 items: list of required arguments and list of optional
                   arguments for creation (in that order)
        """
        if hasattr(self, '_create_attrs'):
            return (self._create_attrs['required'],
                    self._create_attrs['optional'])
        return (tuple(), tuple())

    def create(self, data, **kwargs):
        """Created a new object.

        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)

        Returns:
            RESTObject: a new instance of the manage object class build with
                        the data sent by the server
        """
        self._check_missing_attrs(data)
        if hasattr(self, '_sanitize_data'):
            data = self._sanitize_data(data, 'create')
        server_data = self.gitlab.http_post(self._path, post_data=data, **kwargs)
        return self._obj_cls(self, server_data)


class UpdateMixin(object):
    def _check_missing_attrs(self, data):
        required, optional = self.get_update_attrs()
        missing = []
        for attr in required:
            if attr not in data:
                missing.append(attr)
                continue
        if missing:
            raise AttributeError("Missing attributes: %s" % ", ".join(missing))

    def get_update_attrs(self):
        """Returns the required and optional arguments.

        Returns:
            tuple: 2 items: list of required arguments and list of optional
                   arguments for update (in that order)
        """
        if hasattr(self, '_update_attrs'):
            return (self._update_attrs['required'],
                    self._update_attrs['optional'])
        return (tuple(), tuple())

    def update(self, id=None, new_data={}, **kwargs):
        """Update an object on the server.

        Args:
            id: ID of the object to update (can be None if not required)
            new_data: the update data for the object
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo)

        Returns:
            dict: The new object data (*not* a RESTObject)
        """

        if id is None:
            path = self._path
        else:
            path = '%s/%s' % (self._path, id)

        self._check_missing_attrs(new_data)
        if hasattr(self, '_sanitize_data'):
            data = self._sanitize_data(new_data, 'update')
        server_data = self.gitlab.http_put(self._path, post_data=data,
                                           **kwargs)
        return server_data


class DeleteMixin(object):
    def delete(self, id, **kwargs):
        """Deletes an object on the server.

        Args:
            id: ID of the object to delete
            **kwargs: Extra data to send to the Gitlab server (e.g. sudo)
        """
        path = '%s/%s' % (self._path, id)
        self.gitlab.http_delete(path, **kwargs)


class CRUDMixin(GetMixin, ListMixin, CreateMixin, UpdateMixin, DeleteMixin):
    pass