ci.py 7.23 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python

import os
import re
import glob
import logging
logger = logging.getLogger(__name__)

import click
import pkg_resources
from click_plugins import with_plugins

from . import bdt
from ..log import verbosity_option
from ..ci import is_stable, is_visible_outside
16
from ..constants import SERVER, WEBDAV_PATHS, CACERT
17
from ..webdav3 import client as webdav
André Anjos's avatar
André Anjos committed
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


@with_plugins(pkg_resources.iter_entry_points('bdt.ci.cli'))
@click.group(cls=bdt.AliasedGroup)
def ci():
  """Commands for building packages and handling CI activities

  Commands defined here are supposed to run on our CI, where a number of
  variables that define their behavior is correctly defined.  Do **NOT**
  attempt to run these commands in your own installation.  Unexpected errors
  may occur.
  """
  pass


@ci.command(epilog='''
Examples:

  1. Deploys current build artifacts to the appropriate channels:

     $ bdt ci deploy -vv

''')
@click.option('-d', '--dry-run/--no-dry-run', default=False,
    help='Only goes through the actions, but does not execute them ' \
        '(combine with the verbosity flags - e.g. ``-vvv``) to enable ' \
        'printing to help you understand what will be done')
@verbosity_option()
@bdt.raise_on_error
def deploy(dry_run):
    """Deploys build artifacts (conda packages and sphinx documentation)

    Deployment happens at the "right" locations - conda packages which do not
    represent stable releases are deployed to our conda "beta" channel, while
    stable packages to our root channel.  Sphinx documentation from unstable
    builds (typically the master branch) is deployed to the documentation
    server in a subdirectory named after the current branch name, while stable
    documentation is deployed to a special subdirectory named "stable" and to
    the respective tag name.
    """

    if dry_run:
        logger.warn('!!!! DRY RUN MODE !!!!')
        logger.warn('Nothing is being deployed to server')

    package = os.environ['CI_PROJECT_PATH']

    # determine project visibility
    visible = is_visible_outside(package, os.environ['CI_PROJECT_VISIBILITY'])

    # determine if building master branch or tag - and if tag is on master
    tag = os.environ.get('CI_COMMIT_TAG')
    stable = is_stable(package, os.environ['CI_COMMIT_REF_NAME'], tag)

    server_info = WEBDAV_PATHS[stable][visible]

André Anjos's avatar
André Anjos committed
74
    logger.info('Deploying conda packages to %s%s%s...', SERVER,
André Anjos's avatar
André Anjos committed
75
76
77
78
79
80
81
82
83
        server_info['root'], server_info['conda'])

    # setup webdav connection
    webdav_options = {
        'webdav_hostname': SERVER,
        'webdav_root': server_info['root'],
        'webdav_login': os.environ['DOCUSER'],
        'webdav_password': os.environ['DOCPASS'],
        }
André Anjos's avatar
André Anjos committed
84
    davclient = webdav.Client(webdav_options)
André Anjos's avatar
André Anjos committed
85
86
87
88
89
90
91
92
93
94
95
    assert davclient.valid()

    group, name = package.split('/')

    # uploads conda package artificats
    for arch in ('linux-64', 'osx-64', 'noarch'):
      # finds conda packages and uploads what we can find
      package_path = os.path.join(os.environ['CONDA_ROOT'], 'conda-bld', arch,
          name + '*.tar.bz2')
      deploy_packages = glob.glob(package_path)
      for k in deploy_packages:
96
97
        remote_path = '%s/%s/%s' % (server_info['conda'], arch,
            os.path.basename(k))
André Anjos's avatar
André Anjos committed
98
99
100
101
102
        if davclient.check(remote_path):
          raise RuntimeError('The file %s/%s already exists on the server ' \
              '- this can be due to more than one build with deployment ' \
              'running at the same time.  Re-running the broken builds ' \
              'normally fixes it' % (SERVER, remote_path))
103
104
        logger.info('[dav] %s -> %s%s%s', k, SERVER, server_info['root'],
            remote_path)
André Anjos's avatar
André Anjos committed
105
106
107
108
109
110
111
112
113
114
        if not dry_run:
          davclient.upload(local_path=k, remote_path=remote_path)

    # uploads documentation artifacts
    local_docs = os.path.join(os.environ['CI_PROJECT_DIR'], 'sphinx')
    if not os.path.exists(local_docs):
      raise RuntimeError('Documentation is not available at %s - ' \
          'ensure documentation is being produced for your project!' % \
          local_docs)

115
    remote_path_prefix = '%s/%s' % (server_info['docs'], package)
André Anjos's avatar
André Anjos committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

    # finds out the correct mixture of sub-directories we should deploy to.
    # 1. if ref-name is a tag, don't forget to publish to 'master' as well -
    # all tags are checked to come from that branch
    # 2. if ref-name is a branch name, deploy to it
    # 3. in case a tag is being published, make sure to deploy to the special
    # "stable" subdir as well
    deploy_docs_to = set([os.environ['CI_COMMIT_REF_NAME']])
    if stable:
      deploy_docs_to.add('master')
      if os.environ.get('CI_COMMIT_TAG') is not None:
        deploy_docs_to.add(os.environ['CI_COMMIT_TAG'])
      deploy_docs_to.add('stable')

    for k in deploy_docs_to:
      remote_path = '%s/%s' % (remote_path_prefix, k)
132
133
      logger.info('[dav] %s -> %s%s%s', local_docs, SERVER,
          server_info['root'], remote_path)
André Anjos's avatar
André Anjos committed
134
      if not dry_run:
André Anjos's avatar
André Anjos committed
135
136
        davclient.upload_directory(local_path=local_docs,
            remote_path=remote_path)
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


@ci.command(epilog='''
Examples:

  1. Deploys current build artifacts to the Python Package Index (PyPI):

     $ bdt ci pypi -vv

''')
@click.option('-d', '--dry-run/--no-dry-run', default=False,
    help='Only goes through the actions, but does not execute them ' \
        '(combine with the verbosity flags - e.g. ``-vvv``) to enable ' \
        'printing to help you understand what will be done')
@verbosity_option()
@bdt.raise_on_error
def pypi(dry_run):
    """Deploys build artifacts (python packages to PyPI)

    Deployment is only allowed for packages in which the visibility is
    "public".  This check prevents publishing of private resources to the
    (public) PyPI webserver.
    """

    if dry_run:
        logger.warn('!!!! DRY RUN MODE !!!!')
        logger.warn('Nothing is being deployed to server')

    package = os.environ['CI_PROJECT_PATH']

    # determine project visibility
    visible = is_visible_outside(package, os.environ['CI_PROJECT_VISIBILITY'])

    if not visible:
      raise RuntimeError('The repository %s is not public - a package ' \
          'deriving from it therefore, CANNOT be published to PyPI. ' \
          'You must follow the relevant software disclosure procedures ' \
          'and set this repository to "public" before trying again.' % package)

    # finds the package that should be published
    zip_glob = os.path.join(os.environ['CI_PROJECT_DIR'], 'dist', '*-*.zip')
    zip_files = glob.glob(zip_glob)

    if len(zip_files) == 0:
      raise RuntimeError('Cannot find .zip files on the "dist" directory')

    if len(zip_files) > 1:
      raise RuntimeError('There are %d .zip files on the "dist" directory: ' \
          '%s - I\'m confused on what to publish to PyPI...' % \
          (len(zip_files), ', '.join(zip_files)))

    logger.info('Deploying python package %s to PyPI', zip_files[0])
    #twine upload --skip-existing --username ${PYPIUSER} --password ${PYPIPASS}
    #dist/*.zip
    from twine.settings import Settings

    settings = Settings(
        username=os.environ['PYPIUSER'],
        password=os.environ['PYPIPASS'],
        skip_existing=True,
        cacert=CACERT,
        )

    if not dry_run:
      from twine.commands.upload import upload
      upload(settings, zip_files)
      logger.info('Deployment to PyPI successful')