summaryrefslogtreecommitdiff
path: root/lorrycontroller/gitlab.py
diff options
context:
space:
mode:
Diffstat (limited to 'lorrycontroller/gitlab.py')
-rw-r--r--lorrycontroller/gitlab.py84
1 files changed, 84 insertions, 0 deletions
diff --git a/lorrycontroller/gitlab.py b/lorrycontroller/gitlab.py
new file mode 100644
index 0000000..5c7e579
--- /dev/null
+++ b/lorrycontroller/gitlab.py
@@ -0,0 +1,84 @@
+# Copyright (C) 2016 Codethink Limited
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; version 2 of the License.
+#
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+from __future__ import absolute_import
+import itertools
+try:
+ import gitlab
+except ImportError:
+ gitlab = None
+
+
+class MissingGitlabModuleError(Exception):
+ pass
+
+
+class Gitlab(object):
+
+ '''Run commands on a GitLab instance.
+
+ This uses the python wrapper around the GitLab API.
+ Use of the API requires the private token of a user with master access
+ to the targetted group.
+
+ '''
+
+ def __init__(self, host, token):
+ if gitlab:
+ url = "http://" + host
+ self.gl = gitlab.Gitlab(url, token)
+ else:
+ raise MissingGitlabModuleError('gitlab module missing\n'
+ '\tpython-gitlab is required with GitLab as the git server')
+
+ def first(self, predicate, iterable):
+ return next(itertools.ifilter(predicate, iterable))
+
+ def split_path(self, path):
+ return path.rsplit('/', 1)
+
+ def find_project(self, group, project):
+ predicate = lambda x: x.namespace.name == group and x.name == project
+
+ return self.first(predicate, self.gl.projects.search(project))
+
+ def has_project(self, repo_path):
+ group, project = self.split_path(repo_path)
+
+ try:
+ return bool(self.find_project(group, project))
+ except StopIteration:
+ return False
+
+ def create_project(self, repo_path):
+ group_name, project_name = self.split_path(repo_path)
+ group = None
+ try:
+ group = self.gl.groups.get(group_name)
+ except gitlab.GitlabGetError as e:
+ if e.error_message == '404 Not found':
+ group = self.gl.groups.create(
+ {'name': group_name, 'path': group_name})
+ else:
+ raise
+
+ project = {
+ 'name': project_name,
+ 'public': True,
+ 'merge_requests_enabled': False,
+ 'namespace_id': group.id
+ }
+ self.gl.projects.create(project)
+