gitlab.py 4.29 KB
Newer Older
Alan Marchiori's avatar
Alan Marchiori committed
1
import requests as req
Alan Marchiori's avatar
initial  
Alan Marchiori committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from pprint import pprint
import os.path
import platform

import click
import config
import utils
from config.echo import echo, error, warn

class GitLab:
    def __init__(self):
        self.token = {'private_token': config.UserConfig.getConfig()['api_token']}
        self.url = config.gitlab_url + config.gitlab_api

Alan Marchiori's avatar
Alan Marchiori committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    # wrap requests to always send token and check status_code
    def get(self, url, **kwargs):
        p = dict(self.token, **kwargs)
        r = req.get(url, params=p)
        if r.status_code > 299:
            error("GET {} [{}]: {}.".format(
                url, r.status_code, r.text))
        return r
    def post(self, url, **kwargs):
        p = dict(self.token, **kwargs)
        r = req.post(url, params=p)
        if r.status_code > 299:
            error("POST {} [{}]: {}.".format(
                url, r.status_code, r.text))
        return r
    def delete(self, url, **kwargs):
        p = dict(self.token, **kwargs)
        r = req.delete(url, params=p)
        if r.status_code > 299:
            error("DELETE {} [{}]: {}.".format(
                url, r.status_code, r.text))
        return r

Alan Marchiori's avatar
initial  
Alan Marchiori committed
39
    def get_user(self):
Alan Marchiori's avatar
Alan Marchiori committed
40
41
42
43
44
45
46
47
48
49
50
51
        "get user account details (logged in user)"
        r = self.get(self.url+'user')
        if r.status_code > 299:
            return None
        return r.json()

    def get_users(self, **kwargs):
        "get user account details for OTHER users (not logged in user)"
        r = self.get(self.url+'users', **kwargs)
        if r.status_code > 299:
            return None
        return r.json()
Alan Marchiori's avatar
initial  
Alan Marchiori committed
52
53
54

    def get_keys(self):
        "get all ssh keys on gitlab"
Alan Marchiori's avatar
Alan Marchiori committed
55
56
57
58
        r = self.get(self.url+'user/keys')
        if r.status_code != 200:
            return None
        return r.json()
Alan Marchiori's avatar
initial  
Alan Marchiori committed
59
60
61

    def check_token(self):
        "Make a gitlab API call and check the return code"
Alan Marchiori's avatar
Alan Marchiori committed
62
63
        return self.get_user() != None

Alan Marchiori's avatar
initial  
Alan Marchiori committed
64
65
    def put_key(self, name, key):
        "put a new key on gitlab"
Alan Marchiori's avatar
Alan Marchiori committed
66
        r = self.post(
Alan Marchiori's avatar
initial  
Alan Marchiori committed
67
68
69
70
71
72
73
74
75
76
            self.url+'user/keys',
            data={
            'title': name,
            'key': key})
        return r.status_code

    def ensure_key(self):
        "ensure the local ssh key is on gitlab"
        mykey = utils.ensure_id_rsa()
        found = False
Alan Marchiori's avatar
Alan Marchiori committed
77
        for key in self.get_keys():
Alan Marchiori's avatar
initial  
Alan Marchiori committed
78
79
80
81
82
83
84
85
86
            if mykey==key['key']:
                found = True
                break

        if not found:
            echo("Uploading key to gitlab server.")
            self.put_key(
                name="{}@{}".format(
                    os.environ['USER'],
Alan Marchiori's avatar
Alan Marchiori committed
87
                    platform.node()),
Alan Marchiori's avatar
initial  
Alan Marchiori committed
88
89
                key=mykey)

Alan Marchiori's avatar
Alan Marchiori committed
90
91
92
93
94
95
96
97
98
99
    def search_for_project(self, name, owned=True):
        "search gitlab for the project <name>"
        r = self.get(
                self.url+'projects',
                owned=owned,
                search=name)
        if r.status_code != 200:
            return []
        else:
            return r.json()
Alan Marchiori's avatar
initial  
Alan Marchiori committed
100

Alan Marchiori's avatar
Alan Marchiori committed
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
    def create_project(self, name, **kwargs):
        """create a project on gitalb
        docs: https://docs.gitlab.com/ee/api/projects.html#create-project
        """
        r = self.post(
                self.url+'projects',
                name=name,
                **kwargs)
        # returns the project resource or error codes
        return r.json()
    def remove_project(self, project_id, **kwargs):
        """remove (DELETE) a project on gitalb
        returns True on success
        """
        r = self.delete(
                self.url+'projects/'+str(project_id),
                **kwargs)
        if r.status_code != 202:
            return False
        return True
    def list_members_of_project(self, project_id):
        "return members of project"
        r = self.get(self.url+'projects/'+str(project_id)+'/members')
        if r.status_code != 200:
            return []
        else:
            return r.json()
    def add_member_to_project(self, project_id, user_id, access=10):
        """add user_id to project_id with access
        10 => Guest access
        20 => Reporter access
        30 => Developer access
        40 => Maintainer access
        """
        r = self.post(
                self.url+'projects/'+str(project_id)+'/members',
                user_id=user_id,
                access_level=access)
        if r.status_code > 299:
            return None
        else:
            return r.json()