summaryrefslogtreecommitdiff
path: root/blast.py
blob: b1da8534a9a456e54d5dd59391c4caeb32a36bab (plain) (blame)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#!/usr/bin/env python
import contextlib
import os
import yaml
import subprocess
import sys
from packaging.specifiers import SpecifierSet
from packaging.version import Version, InvalidVersion


USER_CONFIG = os.path.expanduser('~/.blast/config.yaml')
USER_CONFIG_EXISTS = os.path.exists(USER_CONFIG)
SPECIFIERS = ['~', '!', '<', '>', '=']

@contextlib.contextmanager
def use_directory(path):
    prev = os.path.abspath(os.curdir)
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(prev)


class PyEnv:
    def __init__(self, version, venv):
        self.version = version
        self.venv = venv
        self.environ = None

    def _cmd(self, *args, **kwargs):
        if not args:
            raise ValueError('Expecting arguments to pass to pyenv. Got nothing.')

        command = []
        proc = None
        shell = False
        stdout = None
        stderr = None
        env = self.environ

        if kwargs.get('redirect', False):
            stdout = subprocess.PIPE
            stderr = subprocess.PIPE

        if kwargs.get('override', False):
            command = ['pyenv']

        for arg in args:
            command.append(arg)

        if kwargs.get('shell', False):
            shell = True
            command = ' '.join(command)  # convert to string

        try:
            proc = subprocess.run(command, env=env, shell=shell, stdout=stdout, stderr=stderr, check=True, encoding='utf-8')
        except subprocess.CalledProcessError as cpe:
            if cpe.returncode:
                print('Command (exit {}): {}'.format(cpe.returncode, command))
            return cpe

        return proc

    def run(self, *args, **kwargs):
        proc = self._cmd(*args, **kwargs)
        return proc

    def create(self):
        if os.environ.get('PYENV_ROOT'):
            if not os.path.exists(os.path.join(os.environ['PYENV_ROOT'], 'versions', self.version)):
                proc_inst = self._cmd('install', '-s', self.version, override=True)
                if proc_inst.stderr:
                    if not 'already' in proc_inst.stderr:
                        print(proc_inst.stderr)
                        exit(1)

            if not os.path.exists(os.path.join(os.environ['PYENV_ROOT'], 'versions', self.venv)):
                proc_venv = self._cmd('virtualenv', self.version, self.venv, override=True)
        else:
            raise RuntimeError('PYENV_ROOT is not defined.')
            exit(1)


    def activate(self):
        env = {}
        command = 'eval "$(pyenv init -)" ' \
                  '&& eval "$(pyenv virtualenv-init -)" ' \
                  '&& pyenv activate "{}" && pyenv rehash && printenv'.format(self.venv)

        proc = self._cmd(command,
                         shell=True, redirect=True)

        for record in proc.stdout.splitlines():
            if '=' not in record:
                continue
            k, v = record.split('=', 1)
            env[k] = v

        self.environ = env.copy()


class Git:
    def __init__(self, uri):
        self.uri = uri
        self.base = os.path.abspath(os.path.basename(self.uri).replace('.git', ''))
        self.basepath = self.base
        self._tags = []

    def _cmd(self, *args, **kwargs):
        if not args:
            raise ValueError('Expecting arguments to pass to Git. Got nothing.')

        command = ['git']
        proc = None

        for arg in args:
            command.append(arg)

        try:
            proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, encoding='utf-8')
        except subprocess.CalledProcessError as cpe:
            print('Command (exit {}): {}'.format(cpe.returncode, command))
            print(cpe.stderr.strip())
            print(cpe)
            exit(1)

        return proc

    def _has_repo(self):
        if not os.path.exists('.git'):
            raise FileNotFoundError('No git repository present.')
        return True

    def clone(self):
        if os.path.exists(self.basepath):
            return self.basepath

        self._cmd('clone', self.uri)
        return self.basepath

    def fetch(self, *args, **kwargs):
        self._has_repo()
        self._cmd('fetch', *args, *kwargs)

    def checkout(self, ref, **kwargs):
        self._has_repo()
        self._cmd('checkout', ref, **kwargs)

    def reset(self, *args, **kwargs):
        self._has_repo()
        self._cmd('reset', *args, **kwargs)

    def clean(self, *args, **kwargs):
        self._has_repo()
        self._cmd('clean', *args, **kwargs)

    def describe(self, *args, **kwargs):
        self._has_repo()
        result = self._cmd('describe', *args, **kwargs)
        return result.stdout.strip()

    def tag_nearest(self):
        self._has_repo()
        return self.describe('--tags', '--abbrev=0')

    @property
    def tags(self):
        self._has_repo()
        tags = [x.strip() for x in self._cmd('tag', quiet=True).stdout.splitlines()]

        if len(self._tags) == len(tags):
            return self._tags

        self._tags = []  # Clear tags
        for tag in tags:
            self._tags.append(tag)

        return self._tags


def setuptools_inject():
    print("Injecting setuptools...")
    with open('setup.py', 'r') as script:
        orig = script.read().splitlines()

    orig.insert(0, 'import setuptools')

    with open('setup.py', 'w+') as script:
        new = '\n'.join(orig)
        script.write(new)


def eval_specifier(spec, tag, bad_patterns=None):
    # Determine if specifiers are present in spec string
    have_specifier = False
    for ch in spec:
        if ch in SPECIFIERS:
            have_specifier = True

    # When no specifier is present we need to prepend one
    # to satisfy SpecifierSet's basic input requirements
    if not have_specifier:
        spec = '==' + spec

    spec = SpecifierSet(spec)

    # Normalize non-standard tagging conventions
    if bad_patterns is not None:
        for pattern in bad_patterns:
            tag = tag.replace(pattern, '')

    try:
        tag = Version(tag)
    except InvalidVersion as e:
        print("{}".format(e), file=sys.stderr)
        tag = ''

    return tag in spec


if __name__ == '__main__':
    # import argparse
    # from pprint import pprint

    # parser = argparse.ArgumentParser()
    # parser.add_argument('-c', '--config', action='store', default=USER_CONFIG)
    # parser.add_argument('repofile', action='store')

    config = yaml.load("""
    host: https://github.com
    organization: spacetelescope

    global:
        python:
            - 3.5.5
            - 3.6.6
            - 3.7.0

        requires:
            - wheel

        version_latest: true

        version_bad_patterns:
            - 'release_'
            - '_release'
            - 'release-'
            - '-release'

    projects:
        #acstools:
        #    requires:
        #        - relic

        #asdf:
        #    requires: null

        #calcos:
        #    requires: null

        #costools:
        #    requires: null

        #crds:
        #    requires:
        #        - astropy
        #        - numpy
        #        - requests
        #    setuptools_inject: true

        #drizzle:
        #    requires: null

        #drizzlepac:
        #    requires:
        #        - astropy
        #        - numpy

        #fitsblender:
        #    requires: null

        #imexam:
        #    requires: null

        #nictools:
        #    requires: null

        #pysynphot:
        #    requires: null

        reftools:
            requires: null

        relic:
            requires: null

        stistools:
            requires: null

        stsci.convolve:
            requires: null

        stsci.distutils:
            requires: null

        stsci.image:
            requires: null

        stsci.imagemanip:
            requires: null

        stsci.imagestats:
            requires: null

        stsci.ndimage:
            requires: null

        stsci.numdisplay:
            requires: null

        stsci.stimage:
            requires: null

        stsci.skypac:
            requires: null

        stsci.sphere:
            requires: null

        stsci.tools:
            requires: null

        stregion:
            requires: null

        stwcs:
            requires: null

        wfpc2tools:
            requires: null

        wfc3tools:
            requires: null
    """)

    upload_dir = os.path.abspath(os.path.join(os.curdir, 'upload'))
    if not os.path.exists(upload_dir):
        os.mkdir(upload_dir)

    # Begin aliveness checks before we get too far
    check_keys = ['global', 'host', 'organization', 'projects']
    failed_keys = False
    failed_requires = False

    # Check general configuration keys
    for key in check_keys:
        if not config.get(key):
            print('Error: The `{}` key is required.'.format(key), file=sys.stderr)
            failed_keys = True

    if failed_keys:
        exit(1)

    # Check structure of project dictionaries
    for project, info in config['projects'].items():
        print(project, info)
        if info is None and not info.get('requires'):
            print('Error: {}: Missing `requires` list'.format(project), file=sys.stderr)
            failed_requires = True

    if failed_requires:
        exit(1)

    # Perform matrix tasks
    for project, info in config['projects'].items():
        url = '/'.join([config['host'], config['organization'], project])
        repo = Git(url)

        print('Repository: {}'.format(url))
        print('Source directory: {}'.format(repo.basepath))
        try:
            repo.clone()
        except FileNotFoundError as e:
            print('Skipping "{}" due to: {}'.format(project, e))
            continue

        with use_directory(repo.basepath):
            repo.fetch('--all', '--tags')
            for python_version in config['global']['python']:
                tags = []
                venv_name = 'py{}'.format(python_version.replace('.', ''))

                print('=> Using Python {} (virtual: {})...'.format(python_version, venv_name))
                pyenv = PyEnv(python_version, venv_name)
                pyenv.create()
                pyenv.activate()

                # Upgrade PIP
                pyenv.run('pip', 'install', '--upgrade', 'pip', redirect=True)

                # Generic setup
                if config.get('global'):
                    if config['global'].get('requires'):
                        for pkg in config['global']['requires']:
                            pyenv.run('pip', 'install', pkg, redirect=True)

                    if config['global'].get('version_latest'):
                        repo.reset('--hard')
                        repo.clean('-f', '-x', '-d')
                        repo.checkout('master')
                        tags = [repo.tag_nearest()]
                    else:
                        tags = repo.tags

                if info.get('requires'):
                    for pkg in info['requires']:
                        pyenv.run('pip', 'install', pkg)

                for tag in tags:
                    if info.get('build_versions'):
                        spec = info['build_versions']
                        sanitize = None

                        if config['global'].get('version_bad_patterns'):
                            sanitize = config['global']['version_bad_patterns']

                        if info.get('version_bad_patterns'):
                            sanitize += info['version_bad_patterns']

                        if not eval_specifier(spec, tag, sanitize):
                            continue

                    print('==> Building {}::{}'.format(project, tag))

                    repo.reset('--hard')
                    repo.clean('-f', '-x', '-d')
                    repo.checkout(tag)

                    if info.get('setuptools_inject', False):
                        setuptools_inject()

                    for build_command in ['sdist', 'bdist_egg', 'bdist_wheel']:
                        print('===> {}::{}: {}: '.format(project, tag, build_command), end='')
                        proc = pyenv.run('python', 'setup.py', build_command, '-d', upload_dir, redirect=True)
                        if proc.stderr and proc.returncode:
                            print("FAILED")
                            print('#{}'.format('!' * 78))
                            print(proc.stderr)
                            print('#{}'.format('!' * 78))
                        else:
                            print("SUCCESS")