models.py 29.5 KB
Newer Older
1
import json
2
import logging
Guilhem Saurel's avatar
Guilhem Saurel committed
3
import re
4
from subprocess import check_output, CalledProcessError
5

Guilhem Saurel's avatar
Guilhem Saurel committed
6
from django.conf import settings
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
7
from django.db import models
8
from django.template.loader import get_template
Guilhem Saurel's avatar
Guilhem Saurel committed
9
10
from django.utils.dateparse import parse_datetime
from django.utils.safestring import mark_safe
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
11

Guilhem Saurel's avatar
Guilhem Saurel committed
12
import git
Guilhem Saurel's avatar
Guilhem Saurel committed
13
import requests
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
14
from autoslug import AutoSlugField
Guilhem Saurel's avatar
Guilhem Saurel committed
15
from ndh.models import Links, NamedModel, TimeStampedModel
16
from ndh.utils import enum_to_choices, query_sum
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
17

18
from .utils import SOURCES, TARGETS, api_next, slugify_with_dots
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
19

20
21
logger = logging.getLogger('rainboard.models')

Guilhem Saurel's avatar
Guilhem Saurel committed
22
MAIN_BRANCHES = ['master', 'devel']
Guilhem Saurel's avatar
Guilhem Saurel committed
23
24
25
26
27
RPKG_URL = 'http://robotpkg.openrobots.org'
RPKG_LICENSES = {'gnu-lgpl-v3': 'LGPL-3.0', 'gnu-lgpl-v2': 'LGPL-2.0', 'mit': 'MIT', 'gnu-gpl-v3': 'GPL-3.0',
                 '2-clause-bsd': 'BSD-2-Clause'}
RPKG_FIELDS = ['PKGBASE', 'PKGVERSION', 'MASTER_SITES', 'MASTER_REPOSITORY', 'MAINTAINER', 'COMMENT', 'HOMEPAGE']
CMAKE_FIELDS = {'NAME': 'name', 'DESCRIPTION': 'description', 'URL': 'homepage', 'VERSION': 'version'}
Guilhem Saurel's avatar
Guilhem Saurel committed
28
TRAVIS_STATE = {'created': None, 'passed': True, 'started': None, 'failed': False, 'errored': False, 'canceled': False}
Guilhem Saurel's avatar
Guilhem Saurel committed
29
GITLAB_STATUS = {'failed': False, 'success': True, 'pending': None, 'skipped': None, 'canceled': None, 'running': None}
Guilhem Saurel's avatar
Guilhem Saurel committed
30

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
31

Guilhem Saurel's avatar
Guilhem Saurel committed
32
class Article(NamedModel):
Guilhem Saurel's avatar
Guilhem Saurel committed
33
    authors = models.ManyToManyField(settings.AUTH_USER_MODEL)
Guilhem Saurel's avatar
Guilhem Saurel committed
34
35
36
37
38
    year = models.PositiveSmallIntegerField()
    url = models.URLField(max_length=200)
    pdf = models.URLField(max_length=200)


Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
39
class Namespace(NamedModel):
40
    group = models.BooleanField(default=False)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
41
42


Guilhem Saurel's avatar
Guilhem Saurel committed
43
44
45
class License(models.Model):
    name = models.CharField(max_length=200)
    spdx_id = models.CharField(max_length=50, unique=True)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
46
47
48
49
50
51
    url = models.URLField(max_length=200)

    def __str__(self):
        return self.spdx_id or self.name


Guilhem Saurel's avatar
Guilhem Saurel committed
52
class Forge(Links, NamedModel):
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
53
54
55
56
57
    source = models.PositiveSmallIntegerField(choices=enum_to_choices(SOURCES))
    url = models.URLField(max_length=200)
    token = models.CharField(max_length=50, blank=True, null=True)
    verify = models.BooleanField(default=True)

Guilhem Saurel's avatar
Guilhem Saurel committed
58
59
60
    def get_absolute_url(self):
        return self.url

Guilhem Saurel's avatar
Guilhem Saurel committed
61
    def api_req(self, url='', name=None, page=1):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
62
        logger.debug(f'requesting api {self} {url}, page {page}')
63
64
65
66
67
        try:
            return requests.get(self.api_url() + url, {'page': page}, verify=self.verify, headers=self.headers())
        except requests.exceptions.ConnectionError:
            logger.error(f'requesting api {self} {url}, page {page} - SECOND TRY')
            return requests.get(self.api_url() + url, {'page': page}, verify=self.verify, headers=self.headers())
Guilhem Saurel's avatar
Guilhem Saurel committed
68
69
70
71
72
73

    def api_data(self, url=''):
        req = self.api_req(url)
        return req.json() if req.status_code == 200 else []  # TODO

    def api_list(self, url='', name=None):
Guilhem Saurel's avatar
Guilhem Saurel committed
74
75
        page = 1
        while page:
Guilhem Saurel's avatar
Guilhem Saurel committed
76
            req = self.api_req(url, name, page)
Guilhem Saurel's avatar
Guilhem Saurel committed
77
78
79
80
81
            if req.status_code != 200:
                return []  # TODO
            data = req.json()
            if name is not None:
                data = data[name]
Guilhem Saurel's avatar
Guilhem Saurel committed
82
            yield from data
Guilhem Saurel's avatar
Guilhem Saurel committed
83
            page = api_next(self.source, req)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
84
85

    def headers(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
86
87
88
89
90
        return {
            SOURCES.github: {'Authorization': f'token {self.token}', 'Accept':
                             'application/vnd.github.drax-preview+json'},
            SOURCES.gitlab: {'Private-Token': self.token},
            SOURCES.redmine: {'X-Redmine-API-Key': self.token},
Guilhem Saurel's avatar
travis    
Guilhem Saurel committed
91
92
            SOURCES.travis: {'Authorization': f'token {self.token}',
                             'TRAVIS-API-Version': '3'},
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
93
        }[self.source]
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
94
95

    def api_url(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
96
97
98
99
        return {
            SOURCES.github: 'https://api.github.com',
            SOURCES.gitlab: f'{self.url}/api/v4',
            SOURCES.redmine: self.url,
Guilhem Saurel's avatar
travis    
Guilhem Saurel committed
100
            SOURCES.travis: 'https://api.travis-ci.org',
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
101
        }[self.source]
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
102

103
104
    def get_namespaces_github(self):
        for namespace in Namespace.objects.filter(group=True):
Guilhem Saurel's avatar
Guilhem Saurel committed
105
            for data in self.api_list(f'/orgs/{namespace.slug}/members'):
106
107
108
                Namespace.objects.get_or_create(slug=data['login'],
                                                defaults={'name': data['login'], 'group': False})

Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
109
110
111
112
113
114
115
    def get_namespaces_gitlab(self):
        for data in self.api_list('/namespaces'):
            Namespace.objects.get_or_create(slug=data['path'],
                                            defaults={'name': data['name'], 'group': data['kind'] == 'group'})
        for data in self.api_list('/users'):
            Namespace.objects.get_or_create(slug=data['username'], defaults={'name': data['name']})

Guilhem Saurel's avatar
Guilhem Saurel committed
116
117
118
    def get_namespaces_redmine(self):
        pass  # TODO

Guilhem Saurel's avatar
Guilhem Saurel committed
119
120
121
    def get_namespaces_travis(self):
        pass

Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
122
123
124
    def get_projects(self):
        getattr(self, f'get_namespaces_{self.get_source_display()}')()
        return getattr(self, f'get_projects_{self.get_source_display()}')()
125

Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
126
    def get_projects_github(self):
127
        for org in Namespace.objects.filter(group=True):
Guilhem Saurel's avatar
Guilhem Saurel committed
128
            for data in self.api_list(f'/orgs/{org.slug}/repos'):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
129
                update_github(self, org, data)
130
        for user in Namespace.objects.filter(group=False):
Guilhem Saurel's avatar
Guilhem Saurel committed
131
            for data in self.api_list(f'/users/{user.slug}/repos'):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
132
133
                if Project.objects.filter(name=data['name']).exists():
                    update_github(self, user, data)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
134
135

    def get_projects_gitlab(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
136
        for data in self.api_list('/projects'):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
137
            update_gitlab(self, data)
Guilhem Saurel's avatar
Guilhem Saurel committed
138
139

        for orphan in Project.objects.filter(main_namespace=None):
Guilhem Saurel's avatar
git    
Guilhem Saurel committed
140
            repo = orphan.repo_set.filter(forge__source=SOURCES.gitlab).first()
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
141
            update_gitlab(self, self.api_data(f'/projects/{repo.forked_from}'))
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
142
143
144
145

    def get_projects_redmine(self):
        pass  # TODO

Guilhem Saurel's avatar
Guilhem Saurel committed
146
147
148
149
150
151
    def get_projects_travis(self):
        for namespace in Namespace.objects.all():
            for repository in self.api_list(f'/owner/{namespace.slug}/repos', 'repositories'):
                if repository['active']:
                    update_travis(namespace, repository)

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
152

Guilhem Saurel's avatar
Guilhem Saurel committed
153
class Project(Links, NamedModel, TimeStampedModel):
Guilhem Saurel's avatar
Guilhem Saurel committed
154
    public = models.BooleanField(default=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
155
156
157
158
159
    main_namespace = models.ForeignKey(Namespace, on_delete=models.SET_NULL, null=True, blank=True)
    main_forge = models.ForeignKey(Forge, on_delete=models.SET_NULL, null=True, blank=True)
    license = models.ForeignKey(License, on_delete=models.SET_NULL, blank=True, null=True)
    homepage = models.URLField(max_length=200, blank=True, null=True)
    articles = models.ManyToManyField(Article)
Guilhem Saurel's avatar
Guilhem Saurel committed
160
161
    description = models.TextField()
    version = models.CharField(max_length=20, blank=True, null=True)
162
    updated = models.DateTimeField(blank=True, null=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
163
164
    # TODO: release github ↔ robotpkg

Guilhem Saurel's avatar
Guilhem Saurel committed
165
166
167
    def git_path(self):
        return settings.RAINBOARD_GITS / self.main_namespace.slug / self.slug

Guilhem Saurel's avatar
Guilhem Saurel committed
168
    def git(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
169
        path = self.git_path()
Guilhem Saurel's avatar
Guilhem Saurel committed
170
171
172
173
174
        if not path.exists():
            logger.info(f'Creating repo for {self.main_namespace.slug}/{self.slug}')
            return git.Repo.init(path)
        return git.Repo(str(path / '.git'))

175
    def main_repo(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
176
177
        forge = self.main_forge if self.main_forge else get_default_forge(self)
        repo, created = Repo.objects.get_or_create(forge=forge, namespace=self.main_namespace, project=self,
Guilhem Saurel's avatar
Guilhem Saurel committed
178
179
180
                                                   defaults={'name': self.name, 'default_branch': 'master',
                                                             'repo_id': 0})
        if created:
181
            repo.api_update()
Guilhem Saurel's avatar
Guilhem Saurel committed
182
183
        return repo

Guilhem Saurel's avatar
Guilhem Saurel committed
184
    def update_branches(self, main=True, pull=True):
Guilhem Saurel's avatar
Guilhem Saurel committed
185
186
187
        branches = [b[2:] for b in self.git().git.branch('-a', '--no-color').split('\n')]
        if main:
            branches = [b for b in branches if b.endswith('master') or b.endswith('devel')]
Guilhem Saurel's avatar
Guilhem Saurel committed
188
        for branch in branches:
Guilhem Saurel's avatar
Guilhem Saurel committed
189
            logger.info(f'update branch {branch}')
Guilhem Saurel's avatar
Guilhem Saurel committed
190
            if branch in MAIN_BRANCHES:
Guilhem Saurel's avatar
Guilhem Saurel committed
191
                instance, bcreated = Branch.objects.get_or_create(name=branch, project=self)
Guilhem Saurel's avatar
Guilhem Saurel committed
192
            else:
Guilhem Saurel's avatar
Guilhem Saurel committed
193
194
195
                if branch.startswith('remotes/'):
                    branch = branch[8:]
                forge, namespace, name = branch.split('/', maxsplit=2)
Guilhem Saurel's avatar
Guilhem Saurel committed
196
                namespace, _ = Namespace.objects.get_or_create(slug=namespace)
Guilhem Saurel's avatar
Guilhem Saurel committed
197
198
                forge = Forge.objects.get(slug=forge)
                repo, created = Repo.objects.get_or_create(forge=forge, namespace=namespace, project=self,
Guilhem Saurel's avatar
Guilhem Saurel committed
199
200
                                                           defaults={'name': self.name, 'default_branch': 'master',
                                                                     'repo_id': 0})
Guilhem Saurel's avatar
Guilhem Saurel committed
201
202
                if created:
                    repo.api_update()
Guilhem Saurel's avatar
Guilhem Saurel committed
203
204
                instance, bcreated = Branch.objects.get_or_create(name=branch, project=self, repo=repo)
            if bcreated:
Guilhem Saurel's avatar
Guilhem Saurel committed
205
                instance.update(pull=pull)
206

Guilhem Saurel's avatar
Guilhem Saurel committed
207
    def main_branch(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
208
209
210
211
212
213
        heads = self.git().heads
        if heads:
            for branch in MAIN_BRANCHES:
                if branch in heads:
                    return branch
            return heads[0]
Guilhem Saurel's avatar
Guilhem Saurel committed
214

Guilhem Saurel's avatar
Guilhem Saurel committed
215
216
217
218
219
220
221
222
223
224
225
226
    def cmake(self):
        filename = self.git_path() / 'CMakeLists.txt'
        if not filename.exists():
            return
        with filename.open() as f:
            content = f.read()
        for key, value in CMAKE_FIELDS.items():
            search = re.search(f'set\s*\(\s*project_{key}\s+([^)]+)*\)', content, re.I)
            if search:
                self.__dict__[value] = search.groups()[0].strip(''' \r\n\t'"''')
                self.save()

227
228
229
230
231
232
    def repos(self):
        return self.repo_set.count()

    def rpkgs(self):
        return self.robotpkg_set.count()

Guilhem Saurel's avatar
Guilhem Saurel committed
233
234
235
236
    def update_tags(self):
        for tag in self.git().tags:
            Tag.objects.get_or_create(name=str(tag), project=self)

237
    def update(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
238
        self.update_tags()
239
        tag = self.tag_set.filter(name__startswith='v').last()  # TODO: implement SQL ordering for semver
Guilhem Saurel's avatar
Guilhem Saurel committed
240
241
        if tag is not None:
            self.version = tag.name[1:]
242
        robotpkg = self.robotpkg_set.order_by('-updated').first()
Guilhem Saurel's avatar
Guilhem Saurel committed
243
244
245
246
247
248
249
250
        branch = self.branch_set.order_by('-updated').first()
        if branch is not None or robotpkg is not None:
            if robotpkg is None:
                self.updated = branch.updated
            elif branch is None:
                self.updated = robotpkg.updated
            else:
                self.updated = max(branch.updated, robotpkg.updated)
251
252
        self.save()

Guilhem Saurel's avatar
Guilhem Saurel committed
253
    def commits_since(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
254
255
256
257
258
        try:
            commits = self.git().git.rev_list(f'v{self.version}..{self.main_branch()}')
            return len(commits.split('\n')) if commits else 0
        except git.exc.GitCommandError:
            pass
Guilhem Saurel's avatar
Guilhem Saurel committed
259

260
261
262
263
264
265
    def open_issues(self):
        return query_sum(self.repo_set, 'open_issues')

    def open_pr(self):
        return query_sum(self.repo_set, 'open_pr')

266
267
268
    def gitlabciyml(self):
        return get_template('rainboard/gitlab-ci.yml').render({'project': self})

269

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
270
271
class Repo(TimeStampedModel):
    name = models.CharField(max_length=200)
Guilhem Saurel's avatar
Guilhem Saurel committed
272
    slug = AutoSlugField(populate_from='name', slugify=slugify_with_dots)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
273
274
275
276
277
278
279
280
281
282
    forge = models.ForeignKey(Forge, on_delete=models.CASCADE)
    namespace = models.ForeignKey(Namespace, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    license = models.ForeignKey(License, on_delete=models.SET_NULL, blank=True, null=True)
    homepage = models.URLField(max_length=200, blank=True, null=True)
    url = models.URLField(max_length=200, blank=True, null=True)
    default_branch = models.CharField(max_length=50)
    open_issues = models.PositiveSmallIntegerField(blank=True, null=True)
    open_pr = models.PositiveSmallIntegerField(blank=True, null=True)
    repo_id = models.PositiveIntegerField()
Guilhem Saurel's avatar
Guilhem Saurel committed
283
    forked_from = models.PositiveIntegerField(blank=True, null=True)
284
    clone_url = models.URLField(max_length=200)
Guilhem Saurel's avatar
travis    
Guilhem Saurel committed
285
    travis_id = models.PositiveIntegerField(blank=True, null=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
286
287
288

    def __str__(self):
        return self.name
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
289
290

    def api_url(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
291
292
293
294
295
        return {
            SOURCES.github: f'{self.forge.api_url()}/repos/{self.namespace.slug}/{self.slug}',
            SOURCES.redmine: f'{self.forge.api_url()}/projects/{self.repo_id}.json',
            SOURCES.gitlab: f'{self.forge.api_url()}/projects/{self.repo_id}',
        }[self.forge.source]
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
296

Guilhem Saurel's avatar
Guilhem Saurel committed
297
    def api_req(self, url='', name=None, page=1):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
298
        logger.debug(f'requesting api {self.forge} {self.namespace} {self} {url}, page {page}')
299
300
301
302
303
304
305
        try:
            return requests.get(self.api_url() + url, {'page': page}, verify=self.forge.verify,
                                headers=self.forge.headers())
        except requests.exceptions.ConnectionError:
            logger.error(f'requesting api {self.forge} {self.namespace} {self} {url}, page {page} - SECOND TRY')
            return requests.get(self.api_url() + url, {'page': page}, verify=self.forge.verify,
                                headers=self.forge.headers())
Guilhem Saurel's avatar
Guilhem Saurel committed
306
307
308
309
310
311

    def api_data(self, url=''):
        req = self.api_req(url)
        return req.json() if req.status_code == 200 else []  # TODO

    def api_list(self, url='', name=None):
Guilhem Saurel's avatar
Guilhem Saurel committed
312
313
        page = 1
        while page:
Guilhem Saurel's avatar
Guilhem Saurel committed
314
            req = self.api_req(url, name, page)
Guilhem Saurel's avatar
Guilhem Saurel committed
315
316
317
318
            if req.status_code != 200:
                return []  # TODO
            data = req.json()
            if name is not None:
Guilhem Saurel's avatar
Guilhem Saurel committed
319
320
321
322
                if name in data:
                    data = data[name]
                else:
                    return []  # TODO
Guilhem Saurel's avatar
Guilhem Saurel committed
323
            yield from data
Guilhem Saurel's avatar
Guilhem Saurel committed
324
            page = api_next(self.forge.source, req)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
325

Guilhem Saurel's avatar
Guilhem Saurel committed
326
    def api_update(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
327
        data = self.api_data()
Guilhem Saurel's avatar
Guilhem Saurel committed
328
        if data:
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
329
            return getattr(self, f'api_update_{self.forge.get_source_display()}')(data)
Guilhem Saurel's avatar
Guilhem Saurel committed
330
331

    def api_update_gitlab(self, data):
332
        update_gitlab(self.forge, data)
Guilhem Saurel's avatar
Guilhem Saurel committed
333

Guilhem Saurel's avatar
Guilhem Saurel committed
334
    def api_update_github(self, data):
335
        update_github(self.forge, self.namespace, data)
Guilhem Saurel's avatar
Guilhem Saurel committed
336

Guilhem Saurel's avatar
git    
Guilhem Saurel committed
337
338
339
340
341
    def get_clone_url(self):
        if self.forge.source == SOURCES.gitlab:
            return self.clone_url.replace('://', f'://gitlab-ci-token:{self.forge.token}@')
        return self.clone_url

342
343
344
    def git_remote(self):
        return f'{self.forge.slug}/{self.namespace.slug}'

Guilhem Saurel's avatar
git    
Guilhem Saurel committed
345
    def git(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
346
        git_repo = self.project.git()
347
        remote = self.git_remote()
Guilhem Saurel's avatar
git    
Guilhem Saurel committed
348
        try:
Guilhem Saurel's avatar
Guilhem Saurel committed
349
            return git_repo.remote(remote)
Guilhem Saurel's avatar
git    
Guilhem Saurel committed
350
        except ValueError:
Guilhem Saurel's avatar
Guilhem Saurel committed
351
            logger.info(f'Creating remote {remote}')
Guilhem Saurel's avatar
Guilhem Saurel committed
352
            return git_repo.create_remote(remote, self.get_clone_url())
Guilhem Saurel's avatar
git    
Guilhem Saurel committed
353

Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
354
    def fetch(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
355
356
        git_repo = self.git()
        logger.debug(f'fetching {self.forge} / {self.namespace} / {self.project}')
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
357
        try:
Guilhem Saurel's avatar
Guilhem Saurel committed
358
            git_repo.fetch()
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
359
        except git.exc.GitCommandError:
Guilhem Saurel's avatar
Guilhem Saurel committed
360
361
            logger.warning(f'fetching {self.forge} / {self.namespace} / {self.project} - SECOND TRY')
            git_repo.fetch()
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
362

Guilhem Saurel's avatar
Guilhem Saurel committed
363
364
365
    def main_branch(self):
        return self.project.branch_set.get(name=f'{self.git_remote()}/{self.default_branch}')

Guilhem Saurel's avatar
Guilhem Saurel committed
366
    def ahead(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
367
368
        main_branch = self.main_branch()
        return main_branch.ahead if main_branch is not None else 0
Guilhem Saurel's avatar
Guilhem Saurel committed
369
370

    def behind(self):
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
371
372
        main_branch = self.main_branch()
        return main_branch.behind if main_branch is not None else 0
Guilhem Saurel's avatar
Guilhem Saurel committed
373

Guilhem Saurel's avatar
Guilhem Saurel committed
374
375
376
377
    def get_builds(self):
        return getattr(self, f'get_builds_{self.forge.get_source_display()}')()

    def get_builds_gitlab(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
378
        for pipeline in self.api_list('/pipelines'):
Guilhem Saurel's avatar
Guilhem Saurel committed
379
380
381
            pid, ref = pipeline['id'], pipeline['ref']
            if self.project.tag_set.filter(name=ref).exists():
                continue
Guilhem Saurel's avatar
Guilhem Saurel committed
382
            data = self.api_data(f'/pipelines/{pid}')
Guilhem Saurel's avatar
Guilhem Saurel committed
383
384
385
386
387
388
389
390
391
392
393
394
395
            branch_name = f'{self.forge.slug}/{self.namespace.slug}/{ref}'
            branch, created = Branch.objects.get_or_create(name=branch_name, project=self.project, repo=self)
            if created:
                branch.update()
            CIBuild.objects.get_or_create(repo=self, build_id=pid, defaults={
                'passed': GITLAB_STATUS[pipeline['status']],
                'started': parse_datetime(data['created_at']),
                'branch': branch,
            })

    def get_builds_github(self):
        if self.travis_id is not None:
            travis = Forge.objects.get(source=SOURCES.travis)
Guilhem Saurel's avatar
Guilhem Saurel committed
396
            for build in travis.api_list(f'/repo/{self.travis_id}/builds', name='builds'):
Guilhem Saurel's avatar
Guilhem Saurel committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
                if self.project.tag_set.filter(name=build['branch']['name']).exists():
                    continue
                branch_name = f'{self.forge.slug}/{self.namespace.slug}/{build["branch"]["name"]}'
                branch, created = Branch.objects.get_or_create(name=branch_name, project=self.project, repo=self)
                if created:
                    try:
                        branch.update()
                    except git.exc.GitCommandError:
                        # Some guys might delete some branches…
                        # eg. https://travis-ci.org/stack-of-tasks/dynamic-graph/builds/246184885
                        logger.error(f' DELETED BRANCH for {self.project}: {branch_name}')
                        branch.delete()
                        continue
                started = build['started_at'] if build['started_at'] is not None else build['finished_at']
                CIBuild.objects.get_or_create(repo=self, build_id=build['id'], defaults={
                    'passed': TRAVIS_STATE[build['state']],
                    'started': parse_datetime(started),
                    'branch': branch,
                })

    def update(self, pull=True):
        self.project.update_tags()
        if pull:
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
420
            self.fetch()
Guilhem Saurel's avatar
Guilhem Saurel committed
421
422
423
        self.api_update()
        self.get_builds()

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
424
425
426
427

class Commit(NamedModel, TimeStampedModel):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

Guilhem Saurel's avatar
Guilhem Saurel committed
428
429
430
    class Meta:
        unique_together = ('project', 'name')

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
431

Guilhem Saurel's avatar
Guilhem Saurel committed
432
433
434
435
436
class Branch(TimeStampedModel):
    name = models.CharField(max_length=200)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    ahead = models.PositiveSmallIntegerField(blank=True, null=True)
    behind = models.PositiveSmallIntegerField(blank=True, null=True)
437
    updated = models.DateTimeField(blank=True, null=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
438
    repo = models.ForeignKey(Repo, on_delete=models.CASCADE, null=True)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
439
440

    def __str__(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
441
442
443
444
445
446
        return self.name

    class Meta:
        unique_together = ('project', 'name')

    def get_ahead(self, branch='master'):
Guilhem Saurel's avatar
Guilhem Saurel committed
447
448
        commits = self.project.git().git.rev_list(f'{branch}..{self}')
        return len(commits.split('\n')) if commits else 0
Guilhem Saurel's avatar
Guilhem Saurel committed
449
450

    def get_behind(self, branch='master'):
Guilhem Saurel's avatar
Guilhem Saurel committed
451
452
        commits = self.project.git().git.rev_list(f'{self}..{branch}')
        return len(commits.split('\n')) if commits else 0
Guilhem Saurel's avatar
Guilhem Saurel committed
453

454
455
456
    def git(self):
        git_repo = self.project.git()
        if self.name not in git_repo.branches:
Guilhem Saurel's avatar
Guilhem Saurel committed
457
            remote = self.repo.git()
458
459
460
461
462
463
            _, _, branch = self.name.split('/', maxsplit=2)
            git_repo.create_head(self.name, remote.refs[branch]).set_tracking_branch(remote.refs[branch])
        return git_repo.branches[self.name]

    def update(self, pull=True):
        if pull:
Guilhem Saurel's avatar
Guilhem Saurel committed
464
465
466
            self.repo.fetch()
            if self.repo != self.project.main_repo():
                self.project.main_repo().fetch()
Guilhem Saurel's avatar
Guilhem Saurel committed
467
        main_branch = self.project.main_branch()
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
468
469
470
        if main_branch is not None:
            self.ahead = self.get_ahead(main_branch)
            self.behind = self.get_behind(main_branch)
471
        self.updated = self.git().commit.authored_datetime
Guilhem Saurel's avatar
Guilhem Saurel committed
472
        self.save()
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
473

Guilhem Saurel's avatar
Guilhem Saurel committed
474
475
476
477
478
479
480
    def ci(self):
        build = self.cibuild_set.last()
        if build is None:
            return ''
        status = {True: '✓', False: '✗', None: '?'}[build.passed]
        return mark_safe(f'<a href="{build.url()}">{status}</a>')

481
482
483
484
485
486
487
488
    def forge(self):
        if self.repo:
            return self.repo.forge

    def namespace(self):
        if self.repo:
            return self.repo.namespace

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

class Test(TimeStampedModel):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    branch = models.ForeignKey(Branch, on_delete=models.CASCADE)
    commit = models.ForeignKey(Commit, on_delete=models.CASCADE)
    target = models.PositiveSmallIntegerField(choices=enum_to_choices(TARGETS))
    passed = models.BooleanField(default=False)
    # TODO: travis vs gitlab-ci ?
    # TODO: deploy binary, doc, coverage, lint


class SystemDependency(NamedModel):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    target = models.PositiveSmallIntegerField(choices=enum_to_choices(TARGETS))


Guilhem Saurel's avatar
Guilhem Saurel committed
505
class Robotpkg(NamedModel):
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
506
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
Guilhem Saurel's avatar
Guilhem Saurel committed
507
    category = models.CharField(max_length=50)
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
508

Guilhem Saurel's avatar
Guilhem Saurel committed
509
510
511
512
513
514
515
    pkgbase = models.CharField(max_length=50, default='')
    pkgversion = models.CharField(max_length=20, default='')
    master_sites = models.CharField(max_length=200, default='')
    master_repository = models.CharField(max_length=200, default='')
    maintainer = models.CharField(max_length=200, default='')
    comment = models.TextField()
    homepage = models.URLField(max_length=200, default='')
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
516
517

    license = models.ForeignKey(License, on_delete=models.SET_NULL, blank=True, null=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
518
    public = models.BooleanField(default=True)
Guilhem Saurel's avatar
Guilhem Saurel committed
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
    description = models.TextField()
    updated = models.DateTimeField(blank=True, null=True)

    def main_page(self):
        if self.category != 'wip':
            return f'{RPKG_URL}/robotpkg/{self.category}/{self.name}'

    def build_page(self):
        path = '-wip/wip' if self.category == 'wip' else f'/{self.category}'
        return f'{RPKG_URL}/rbulk/robotpkg{path}/{self.name}'

    def update(self, pull=True):
        path = settings.RAINBOARD_RPKG
        repo = git.Repo(str(path / 'wip' / '.git' if self.category == 'wip' else path / '.git'))
        if pull:
            repo.remotes.origin.pull()

        cwd = path / self.category / self.name
        for field in RPKG_FIELDS:
            cmd = ['make', 'show-var', f'VARNAME={field}']
            self.__dict__[field.lower()] = check_output(cmd, cwd=cwd).decode().strip()

        repo_path = self.name if self.category == 'wip' else f'{self.category}/{self.name}'
        last_commit = next(repo.iter_commits(paths=repo_path, max_count=1))
        self.updated = last_commit.authored_datetime

        license = check_output(['make', 'show-var', f'VARNAME=LICENSE'], cwd=cwd).decode().strip()
        if license in RPKG_LICENSES:
            self.license = License.objects.get(spdx_id=RPKG_LICENSES[license])
        else:
            logger.warning(f'Unknown robotpkg license: {license}')
Guilhem Saurel's avatar
Guilhem Saurel committed
550
        self.public = not bool(check_output(['make', 'show-var', f'VARNAME=RESTRICTED'], cwd=cwd).decode().strip())
Guilhem Saurel's avatar
Guilhem Saurel committed
551
552
553
        with (cwd / 'DESCR').open() as f:
            self.description = f.read().strip()

554
555
556
557
558
        for target in TARGETS:
            image, created = Image.objects.get_or_create(robotpkg=self, target=target)
            if created:
                image.update()

Guilhem Saurel's avatar
Guilhem Saurel committed
559
        self.save()
Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
560

561
562
563
    def valid_images(self):
        return self.image_set.filter(created__isnull=False)

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
564
565
566
567
568
569
570

class RobotpkgBuild(TimeStampedModel):
    robotpkg = models.ForeignKey(Robotpkg, on_delete=models.CASCADE)
    target = models.PositiveSmallIntegerField(choices=enum_to_choices(TARGETS))
    passed = models.BooleanField(default=False)


571
572
573
574
575
576
577
578
579
580
581
582
583
class Image(models.Model):
    robotpkg = models.ForeignKey(Robotpkg, on_delete=models.CASCADE)
    target = models.PositiveSmallIntegerField(choices=enum_to_choices(TARGETS))
    created = models.DateTimeField(blank=True, null=True)
    image = models.CharField(max_length=12, blank=True, null=True)

    class Meta:
        unique_together = ('robotpkg', 'target')

    def __str__(self):
        return f'{self.robotpkg}-{self.get_target_display()}'

    def get_build_args(self):
Guilhem Saurel's avatar
Guilhem Saurel committed
584
585
586
587
        ret = {'TARGET': self.get_target_display(), 'ROBOTPKG': self.robotpkg}
        if not self.robotpkg.project.public:
            ret['IMAGE'] = 'robotpkg-jrl'
        return ret
588
589
590
591
592
593
594
595

    def get_image_name(self):
        project = self.robotpkg.project
        return f'{settings.REGISTRY}/{project.main_namespace.slug}/{project}:{self.get_target_display()}'

    def build(self):
        args = self.get_build_args()
        build_args = sum((['--build-arg', f'{key}={value}'] for key, value in args.items()), list())
596
597
598
599
600
601
602
        return ['docker', 'build', '-t', self.get_image_name()] + build_args + ['.']

    def pull(self):
        return ['docker', 'pull', self.get_image_name()]

    def push(self):
        return ['docker', 'push', self.get_image_name()]
603

Guilhem Saurel's avatar
Guilhem Saurel committed
604
    def update(self, pull=False):
605
606
        image = check_output(['docker', 'images', '-q', self.get_image_name()]).decode().strip()
        if not image:
Guilhem Saurel's avatar
Guilhem Saurel committed
607
608
            if not pull:
                return
609
610
            try:
                logger.info(f' pulling {self}')
611
                check_output(self.pull())
612
613
614
615
616
617
618
619
                image = check_output(['docker', 'images', '-q', self.get_image_name()]).decode().strip()
            except CalledProcessError:
                return
        self.image = image
        self.created = parse_datetime(json.loads(check_output(['docker', 'inspect', image]))[0]['Created'])
        self.save()


Guilhem Saurel's avatar
Guilhem Saurel committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
class CIBuild(models.Model):
    repo = models.ForeignKey(Repo, on_delete=models.CASCADE)
    passed = models.NullBooleanField()
    build_id = models.PositiveIntegerField()
    started = models.DateTimeField()
    branch = models.ForeignKey(Branch, on_delete=models.CASCADE)

    class Meta:
        ordering = ('started',)

    def url(self):
        if self.repo.forge.source == SOURCES.github:
            return f'https://travis-ci.org/{self.repo.namespace.slug}/{self.repo.slug}/builds/{self.build_id}'
        if self.repo.forge.source == SOURCES.gitlab:
            return f'{self.repo.forge.url}/{self.repo.namespace.slug}/{self.repo.slug}/pipelines/{self.build_id}'


class Tag(models.Model):
    name = models.CharField(max_length=200)
    slug = AutoSlugField(populate_from='name', slugify=slugify_with_dots)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

    class Meta:
        ordering = ('name',)
        unique_together = ('name', 'project')

Guilhem Saurel's avatar
initial  
Guilhem Saurel committed
646
647
648
649
# TODO: later
# class Dockerfile(NamedModel, TimeStampedModel):
    # project = models.ForeignKey(Project, on_delete=models.CASCADE)
    # target = models.PositiveSmallIntegerField(choices=enum_to_choices(TARGETS))
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664


def get_default_forge(project):
    for forge in Forge.objects.order_by('source'):
        if project.repo_set.filter(forge=forge).exists():
            logger.info(f'default forge for {project} set to {forge}')
            project.main_forge = forge
            project.save()
            return forge
    else:
        logger.error(f'NO DEFAULT FORGE for {project}')


def update_gitlab(forge, data):
    logger.info(f'update {data["name"]} from {forge}')
Guilhem Saurel's avatar
Guilhem Saurel committed
665
    public = data['visibility'] not in ['private', 'internal']
Guilhem Saurel's avatar
Guilhem Saurel committed
666
    project, created = Project.objects.get_or_create(name=data['name'],
Guilhem Saurel's avatar
Guilhem Saurel committed
667
                                                     defaults={'main_forge': forge, 'public': public})
Guilhem Saurel's avatar
Guilhem Saurel committed
668
669
    namespace, _ = Namespace.objects.get_or_create(slug=data['namespace']['path'],
                                                   defaults={'name': data['namespace']['name']})
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
670
    repo, _ = Repo.objects.get_or_create(forge=forge, namespace=namespace, project=project,
671
672
673
674
675
676
677
678
679
680
681
                                         defaults={'repo_id': data['id'], 'name': data['name'], 'url': data['web_url'],
                                                   'default_branch': data['default_branch'],
                                                   'clone_url': data['http_url_to_repo']})
    repo.name = data['name']
    repo.slug = data['path']
    repo.url = data['web_url']
    repo.repo_id = data['id']
    repo.clone_url = data['http_url_to_repo']
    repo.open_issues = data['open_issues_count']
    repo.default_branch = data['default_branch']
    # TODO license, open_pr, homepage
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
682
683
684
685
686
    if 'forked_from_project' in data:
        repo.forked_from = data['forked_from_project']['id']
    elif created or project.main_namespace is None:
        project.main_namespace = namespace
        project.save()
687
    repo.save()
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
688
689
690
691
692
693
694


def update_github(forge, namespace, data):
    logger.info(f'update {data["name"]} from {forge}')
    project, _ = Project.objects.get_or_create(name=data['name'], defaults={
        'homepage': data['homepage'], 'main_namespace': namespace, 'main_forge': forge})
    repo, _ = Repo.objects.get_or_create(forge=forge, namespace=namespace, project=project,
695
696
                                         defaults={'repo_id': data['id'], 'name': data['name'],
                                                   'clone_url': data['clone_url']})
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
697
698
699
700
701
702
703
704
705
706
707
708
709
    repo.homepage = data['homepage']
    repo.url = data['html_url']
    repo.repo_id = data['id']
    repo.default_branch = data['default_branch']
    repo.open_issues = data['open_issues']

    repo_data = repo.api_data()
    if repo_data and 'license' in repo_data and repo_data['license']:
        if 'spdx_id' in repo_data['license'] and repo_data['license']['spdx_id']:
            license = License.objects.get(spdx_id=repo_data['license']['spdx_id'])
            repo.license = license
            if not project.license:
                project.license = license
710
711
712
713
        if 'source' in repo_data:
            repo.forked_from = repo_data['source']['id']
    repo.open_issues = repo_data['open_issues_count']
    repo.clone_url = data['clone_url']
Guilhem Saurel's avatar
clean    
Guilhem Saurel committed
714
715
716
    repo.open_pr = len(list(repo.api_list('/pulls')))
    repo.save()
    project.save()
Guilhem Saurel's avatar
Guilhem Saurel committed
717
718
719
720
721
722
723
724
725
726
727
728
729
730


def update_travis(namespace, data):
    project = Project.objects.filter(name=data['name']).first()
    if project is None:
        return
    forge = Forge.objects.get(source=SOURCES.github)
    repo, created = Repo.objects.get_or_create(forge=forge, namespace=namespace, project=project,
                                               defaults={'name': data['name'], 'repo_id': 0, 'travis_id': data['id']})
    if created:
        repo.api_update()
    else:
        repo.travis_id = data['id']
        repo.save()