File: version_helpers.py

package info (click to toggle)
python-astropy-helpers 0.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 540 kB
  • ctags: 584
  • sloc: python: 5,173; ansic: 88; makefile: 11
file content (205 lines) | stat: -rw-r--r-- 6,384 bytes parent folder | download
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
# Licensed under a 3-clause BSD style license - see LICENSE.rst

"""
Utilities for generating the version string for Astropy (or an affiliated
package) and the version.py module, which contains version info for the
package.

Within the generated astropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absent). The `release` variable is True if this is a release, and False if this
is a development version of astropy. For the actual version string, use::

    from astropy.version import version

or::

    from astropy import __version__

"""

from __future__ import division

import datetime
import imp
import os
import pkgutil
import sys

from distutils import log

from . import git_helpers
from .setup_helpers import is_distutils_display_option, get_pkg_version_module
from .utils import invalidate_caches

PY3 = sys.version_info[0] == 3



def _version_split(version):
    """
    Split a version string into major, minor, and bugfix numbers (with bugfix
    optional, defaulting to 0).
    """

    for prerel in ('.dev', 'a', 'b', 'rc'):
        if prerel in version:
            version = version.split(prerel)[0]

    versplit = version.split('.')
    major = int(versplit[0])
    minor = int(versplit[1])
    bugfix = 0 if len(versplit) < 3 else int(versplit[2])
    return major, minor, bugfix


# This is used by setup.py to create a new version.py - see that file for
# details. Note that the imports have to be absolute, since this is also used
# by affiliated packages.
_FROZEN_VERSION_PY_TEMPLATE = """
# Autogenerated by {packagename}'s setup.py on {timestamp}

{header}

major = {major}
minor = {minor}
bugfix = {bugfix}

release = {rel}
debug = {debug}

try:
    from ._compiler import compiler
except ImportError:
    compiler = "unknown"

try:
    from .cython_version import cython_version
except ImportError:
    cython_version = "unknown"
"""[1:]


_FROZEN_VERSION_PY_WITH_GIT_HEADER = """
{git_helpers}

_last_generated_version = {verstr!r}
_last_githash = {githash!r}

version = update_git_devstr(_last_generated_version)
githash = get_git_devstr(sha=True, show_warning=False,
                         path=__file__) or _last_githash
"""[1:]


def _get_version_py_str(packagename, version, githash, release, debug,
                        uses_git=True):
    timestamp = str(datetime.datetime.now())
    major, minor, bugfix = _version_split(version)

    if packagename.lower() == 'astropy':
        packagename = 'Astropy'
    else:
        packagename = 'Astropy-affiliated package ' + packagename

    if uses_git:
        loader = pkgutil.get_loader(git_helpers)
        source = loader.get_source(git_helpers.__name__) or ''
        source_lines = source.splitlines()
        if not source_lines:
            log.warn('Cannot get source code for astropy_helpers.git_helpers; '
                     'git support disabled.')
            return _get_version_py_str(packagename, version, release, debug,
                                       uses_git=False)
        idx = 0
        for idx, line in enumerate(source_lines):
            if line.startswith('# BEGIN'):
                break
        git_helpers_py = '\n'.join(source_lines[idx + 1:])

        if PY3:
            verstr = version
        else:
            # In Python 2 don't pass in a unicode string; otherwise verstr will
            # be represented with u'' syntax which breaks on Python 3.x with x
            # < 3.  This is only an issue when developing on multiple Python
            # versions at once
            verstr = version.encode('utf8')

        new_githash = git_helpers.get_git_devstr(sha=True, show_warning=False)

        if new_githash:
            githash = new_githash

        header = _FROZEN_VERSION_PY_WITH_GIT_HEADER.format(
                git_helpers=git_helpers_py,
                verstr=verstr, githash=githash)
    else:
        header = 'version = {0!r}'.format(version)

    return _FROZEN_VERSION_PY_TEMPLATE.format(packagename=packagename,
                                              timestamp=timestamp,
                                              header=header,
                                              major=major,
                                              minor=minor,
                                              bugfix=bugfix,
                                              rel=release, debug=debug)


def generate_version_py(packagename, version, release=None, debug=None,
                        uses_git=True):
    """Regenerate the version.py module if necessary."""

    try:
        version_module = get_pkg_version_module(packagename)

        try:
            last_generated_version = version_module._last_generated_version
        except AttributeError:
            last_generated_version = version_module.version

        try:
            last_githash = version_module._last_githash
        except AttributeError:
            last_githash = ''

        current_release = version_module.release
        current_debug = version_module.debug
    except ImportError:
        version_module = None
        last_generated_version = None
        last_githash = None
        current_release = None
        current_debug = None

    if release is None:
        # Keep whatever the current value is, if it exists
        release = bool(current_release)

    if debug is None:
        # Likewise, keep whatever the current value is, if it exists
        debug = bool(current_debug)

    version_py = os.path.join(packagename, 'version.py')

    if (last_generated_version != version or current_release != release or
        current_debug != debug):
        if '-q' not in sys.argv and '--quiet' not in sys.argv:
            log.set_threshold(log.INFO)

        if is_distutils_display_option():
            # Always silence unnecessary log messages when display options are
            # being used
            log.set_threshold(log.WARN)

        log.info('Freezing version number to {0}'.format(version_py))

        with open(version_py, 'w') as f:
            # This overwrites the actual version.py
            f.write(_get_version_py_str(packagename, version, last_githash,
                                        release, debug, uses_git=uses_git))

        invalidate_caches()

        if version_module:
            imp.reload(version_module)