aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/incremental/py2/incremental/update.py
blob: 64a5cc84e79afb1385775fe99fb759a12e713603 (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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from __future__ import absolute_import, division, print_function

import click
import os
import datetime
from typing import TYPE_CHECKING, Dict, Optional, Callable, Iterable

from incremental import Version

if TYPE_CHECKING:
    from typing_extensions import Protocol

    class _ReadableWritable(Protocol):
        def read(self):  # type: () -> bytes
            pass

        def write(self, v):  # type: (bytes) -> object
            pass

        def __enter__(self):  # type: () -> _ReadableWritable
            pass

        def __exit__(self, *args, **kwargs):  # type: (object, object) -> Optional[bool]
            pass

    # FilePath is missing type annotations
    # https://twistedmatrix.com/trac/ticket/10148
    class FilePath(object):
        def __init__(self, path):  # type: (str) -> None
            self.path = path

        def child(self, v):  # type: (str) -> FilePath
            pass

        def isdir(self):  # type: () -> bool
            pass

        def isfile(self):  # type: () -> bool
            pass

        def getContent(self):  # type: () -> bytes
            pass

        def open(self, mode):  # type: (str) -> _ReadableWritable
            pass

        def walk(self):  # type: () -> Iterable[FilePath]
            pass


else:
    from twisted.python.filepath import FilePath

_VERSIONPY_TEMPLATE = '''"""
Provides {package} version information.
"""

# This file is auto-generated! Do not edit!
# Use `python -m incremental.update {package}` to change this file.

from incremental import Version

__version__ = {version_repr}
__all__ = ["__version__"]
'''

_YEAR_START = 2000


def _findPath(path, package):  # type: (str, str) -> FilePath

    cwd = FilePath(path)

    src_dir = cwd.child("src").child(package.lower())
    current_dir = cwd.child(package.lower())

    if src_dir.isdir():
        return src_dir
    elif current_dir.isdir():
        return current_dir
    else:
        raise ValueError(
            "Can't find under `./src` or `./`. Check the "
            "package name is right (note that we expect your "
            "package name to be lower cased), or pass it using "
            "'--path'."
        )


def _existing_version(path):  # type: (FilePath) -> Version
    version_info = {}  # type: Dict[str, Version]

    with path.child("_version.py").open("r") as f:
        exec(f.read(), version_info)

    return version_info["__version__"]


def _run(
    package,  # type: str
    path,  # type: Optional[str]
    newversion,  # type: Optional[str]
    patch,  # type: bool
    rc,  # type: bool
    post,  # type: bool
    dev,  # type: bool
    create,  # type: bool
    _date=None,  # type: Optional[datetime.date]
    _getcwd=None,  # type: Optional[Callable[[], str]]
    _print=print,  # type: Callable[[object], object]
):  # type: (...) -> None

    if not _getcwd:
        _getcwd = os.getcwd

    if not _date:
        _date = datetime.date.today()

    if type(package) != str:
        package = package.encode("utf8")  # type: ignore[assignment]

    _path = FilePath(path) if path else _findPath(_getcwd(), package)

    if (
        newversion
        and patch
        or newversion
        and dev
        or newversion
        and rc
        or newversion
        and post
    ):
        raise ValueError("Only give --newversion")

    if dev and patch or dev and rc or dev and post:
        raise ValueError("Only give --dev")

    if (
        create
        and dev
        or create
        and patch
        or create
        and rc
        or create
        and post
        or create
        and newversion
    ):
        raise ValueError("Only give --create")

    if newversion:
        from pkg_resources import parse_version

        existing = _existing_version(_path)
        st_version = parse_version(newversion)._version  # type: ignore[attr-defined]

        release = list(st_version.release)

        minor = 0
        micro = 0
        if len(release) == 1:
            (major,) = release
        elif len(release) == 2:
            major, minor = release
        else:
            major, minor, micro = release

        v = Version(
            package,
            major,
            minor,
            micro,
            release_candidate=st_version.pre[1] if st_version.pre else None,
            post=st_version.post[1] if st_version.post else None,
            dev=st_version.dev[1] if st_version.dev else None,
        )

    elif create:
        v = Version(package, _date.year - _YEAR_START, _date.month, 0)
        existing = v

    elif rc and not patch:
        existing = _existing_version(_path)

        if existing.release_candidate:
            v = Version(
                package,
                existing.major,
                existing.minor,
                existing.micro,
                existing.release_candidate + 1,
            )
        else:
            v = Version(package, _date.year - _YEAR_START, _date.month, 0, 1)

    elif patch:
        existing = _existing_version(_path)
        v = Version(
            package,
            existing.major,
            existing.minor,
            existing.micro + 1,
            1 if rc else None,
        )

    elif post:
        existing = _existing_version(_path)

        if existing.post is None:
            _post = 0
        else:
            _post = existing.post + 1

        v = Version(package, existing.major, existing.minor, existing.micro, post=_post)

    elif dev:
        existing = _existing_version(_path)

        if existing.dev is None:
            _dev = 0
        else:
            _dev = existing.dev + 1

        v = Version(
            package,
            existing.major,
            existing.minor,
            existing.micro,
            existing.release_candidate,
            dev=_dev,
        )

    else:
        existing = _existing_version(_path)

        if existing.release_candidate:
            v = Version(package, existing.major, existing.minor, existing.micro)
        else:
            raise ValueError("You need to issue a rc before updating the major/minor")

    NEXT_repr = repr(Version(package, "NEXT", 0, 0)).split("#")[0].replace("'", '"')
    NEXT_repr_bytes = NEXT_repr.encode("utf8")

    version_repr = repr(v).split("#")[0].replace("'", '"')
    version_repr_bytes = version_repr.encode("utf8")

    existing_version_repr = repr(existing).split("#")[0].replace("'", '"')
    existing_version_repr_bytes = existing_version_repr.encode("utf8")

    _print("Updating codebase to %s" % (v.public()))

    for x in _path.walk():

        if not x.isfile():
            continue

        original_content = x.getContent()
        content = original_content

        # Replace previous release_candidate calls to the new one
        if existing.release_candidate:
            content = content.replace(existing_version_repr_bytes, version_repr_bytes)
            content = content.replace(
                (package.encode("utf8") + b" " + existing.public().encode("utf8")),
                (package.encode("utf8") + b" " + v.public().encode("utf8")),
            )

        # Replace NEXT Version calls with the new one
        content = content.replace(NEXT_repr_bytes, version_repr_bytes)
        content = content.replace(
            NEXT_repr_bytes.replace(b"'", b'"'), version_repr_bytes
        )

        # Replace <package> NEXT with <package> <public>
        content = content.replace(
            package.encode("utf8") + b" NEXT",
            (package.encode("utf8") + b" " + v.public().encode("utf8")),
        )

        if content != original_content:
            _print("Updating %s" % (x.path,))
            with x.open("w") as f:
                f.write(content)

    _print("Updating %s/_version.py" % (_path.path))
    with _path.child("_version.py").open("w") as f:
        f.write(
            (
                _VERSIONPY_TEMPLATE.format(package=package, version_repr=version_repr)
            ).encode("utf8")
        )


@click.command()
@click.argument("package")
@click.option("--path", default=None)
@click.option("--newversion", default=None)
@click.option("--patch", is_flag=True)
@click.option("--rc", is_flag=True)
@click.option("--post", is_flag=True)
@click.option("--dev", is_flag=True)
@click.option("--create", is_flag=True)
def run(
    package,  # type: str
    path,  # type: Optional[str]
    newversion,  # type: Optional[str]
    patch,  # type: bool
    rc,  # type: bool
    post,  # type: bool
    dev,  # type: bool
    create,  # type: bool
):  # type: (...) -> None
    return _run(
        package=package,
        path=path,
        newversion=newversion,
        patch=patch,
        rc=rc,
        post=post,
        dev=dev,
        create=create,
    )


if __name__ == "__main__":  # pragma: no cover
    run()