File: release.py

package info (click to toggle)
pipenv 2024.0.1%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,568 kB
  • sloc: python: 187,163; makefile: 191; javascript: 133; sh: 64
file content (299 lines) | stat: -rw-r--r-- 9,429 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
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
import datetime
import os
import pathlib
import re
import subprocess
import sys

import invoke
import semver

from pipenv.__version__ import __version__
from pipenv.utils.shell import temp_environ

from .vendoring import _get_git_root, drop_dir

VERSION_FILE = "pipenv/__version__.py"
ROOT = pathlib.Path(".").parent.parent.absolute()
PACKAGE_NAME = "pipenv"


def log(msg):
    print(f"[release] {msg}")


def get_version_file(ctx):
    return _get_git_root(ctx).joinpath(VERSION_FILE)


def find_version(ctx):
    version_file = get_version_file(ctx).read_text()
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")


def get_history_file(ctx):
    return _get_git_root(ctx).joinpath("HISTORY.txt")


def get_dist_dir(ctx):
    return _get_git_root(ctx) / "dist"


def get_build_dir(ctx):
    return _get_git_root(ctx) / "build"


def _render_log():
    """Totally tap into Towncrier internals to get an in-memory result."""
    rendered = subprocess.check_output(["towncrier", "--draft"]).decode("utf-8")
    return rendered


release_help = {
    "dry_run": "No-op, simulate what would happen if run for real.",
    "pre": "Build a pre-release version, must be paired with a tag.",
}


@invoke.task(help=release_help)
def release(
    ctx,
    dry_run=False,
    pre=False,
):
    drop_dist_dirs(ctx)
    version = bump_version(
        ctx,
        dry_run=dry_run,
        pre=pre,
    )
    tag_content = _render_log()
    if dry_run:
        ctx.run("towncrier --draft > CHANGELOG.draft.md")
        log("would remove: news/*")
        log("would remove: CHANGELOG.draft.md")
        log("would update: pipenv/pipenv.1")
        log(f'Would commit with message: "Release v{version}"')
    else:
        if pre:
            log("generating towncrier draft...")
            ctx.run("towncrier --draft > CHANGELOG.draft.md")
            ctx.run(f"git add {get_version_file(ctx).as_posix()}")
        else:
            ctx.run("towncrier")
            ctx.run(f"git add CHANGELOG.md news/ {get_version_file(ctx).as_posix()}")
            log("removing changelog draft if present")
            draft_changelog = pathlib.Path("CHANGELOG.draft.md")
            if draft_changelog.exists():
                draft_changelog.unlink()
        log("generating man files...")
        generate_manual(ctx)
        ctx.run("git add pipenv/pipenv.1")
        ctx.run(f'git commit -m "Release v{version}"')

    tag_content = tag_content.replace('"', '\\"')
    if dry_run or pre:
        log(f"Generated tag content: {tag_content}")
        # draft_rstfile = "CHANGELOG.draft.rst"
        # markdown_path = pathlib.Path(draft_rstfile).with_suffix(".md")
        # generate_markdown(ctx, source_rstfile=draft_rstfile)
        # clean_mdchangelog(ctx, markdown_path.as_posix())
        # log(f"would generate markdown: {markdown_path.read_text()}")
        if not dry_run:
            ctx.run(f'git tag -a v{version} -m "Version v{version}\n\n{tag_content}"')
    else:
        # generate_markdown(ctx)
        # clean_mdchangelog(ctx)
        ctx.run(f'git tag -a v{version} -m "Version v{version}\n\n{tag_content}"')


def drop_dist_dirs(ctx):
    log("Dropping Dist dir...")
    drop_dir(get_dist_dir(ctx))
    log("Dropping build dir...")
    drop_dir(get_build_dir(ctx))


@invoke.task
def build_dists(ctx):
    drop_dist_dirs(ctx)
    py_version = ".".join(str(v) for v in sys.version_info[:2])
    env = {"PIPENV_PYTHON": py_version}
    with ctx.cd(ROOT.as_posix()), temp_environ():
        executable = ctx.run(
            "python -c 'import sys; print(sys.executable)'", hide=True
        ).stdout.strip()
        log(f"Building sdist using {executable} ....")
        os.environ["PIPENV_PYTHON"] = py_version
        ctx.run("pipenv install --dev", env=env)
        ctx.run("pipenv run pip install -e . --upgrade --upgrade-strategy=eager", env=env)
        log(f"Building wheel using python {py_version} ....")
        ctx.run("pipenv run python -m build", env=env)


@invoke.task(build_dists)
def upload_dists(ctx, repo="pypi"):
    dist_pattern = f'{PACKAGE_NAME.replace("-", "[-_]")}-*'
    artifacts = list(ROOT.joinpath("dist").glob(dist_pattern))
    filename_display = "\n".join(f"  {a}" for a in artifacts)
    print(f"[release] Will upload:\n{filename_display}")
    try:
        input("[release] Release ready. ENTER to upload, CTRL-C to abort: ")
    except KeyboardInterrupt:
        print("\nAborted!")
        return

    arg_display = " ".join(f'"{n}"' for n in artifacts)
    ctx.run(f'twine upload --repository="{repo}" {arg_display}')


@invoke.task
def generate_markdown(ctx, source_rstfile=None):
    log("Generating markdown from changelog...")
    if source_rstfile is None:
        source_rstfile = "CHANGELOG.md"
    source_file = pathlib.Path(source_rstfile)
    dest_file = source_file.with_suffix(".md")
    ctx.run(
        f"pandoc {source_file.as_posix()} -f rst -t markdown -o {dest_file.as_posix()}"
    )


@invoke.task
def generate_manual(ctx, commit=False):
    log("Generating manual from reStructuredText source...")
    ctx.run("make man")
    ctx.run("cp docs/_build/man/pipenv.1 pipenv/")
    if commit:
        log("Committing...")
        ctx.run("git add pipenv/pipenv.1")
        ctx.run('git commit -m "Update manual page."')


@invoke.task
def generate_contributing_md(ctx, commit=False):
    log("Generating CONTRIBUTING.md from reStructuredText source...")
    ctx.run("pandoc docs/dev/contributing.rst -f rst -t markdown -o CONTRIBUTING.md")
    if commit:
        log("Committing...")
        ctx.run("git add CONTRIBUTING.md")
        ctx.run('git commit -m "Update CONTRIBUTING.md."')


@invoke.task
def generate_changelog(ctx, commit=False, draft=False):
    log("Generating changelog...")
    if draft:
        commit = False
        log("Writing draft to file...")
        ctx.run("towncrier --draft > CHANGELOG.draft.md")
    else:
        ctx.run("towncrier")
    if commit:
        log("Committing...")
        ctx.run("git add CHANGELOG.md")
        ctx.run("git rm CHANGELOG.draft.md")
        ctx.run('git commit -m "Update changelog."')


@invoke.task
def clean_mdchangelog(ctx, filename=None, content=None):
    changelog = None
    if not content:
        if filename is not None:
            changelog = pathlib.Path(filename)
        else:
            changelog = _get_git_root(ctx) / "CHANGELOG.md"
        content = changelog.read_text()
    content = re.sub(
        r"([^\n]+)\n?\s+\[[\\]+(#\d+)\]\(https://github\.com/pypa/[\w\-]+/issues/\d+\)",
        r"\1 \2",
        content,
        flags=re.MULTILINE,
    )
    if changelog:
        changelog.write_text(content)
    else:
        return content


@invoke.task
def tag_version(ctx, push=False):
    version = find_version(ctx)
    version = semver.VersionInfo.parse(version)
    log(f"Tagging revision: v{version}")
    ctx.run(f"git tag v{version}")
    if push:
        log("Pushing tags...")
        ctx.run("git push origin master")
        ctx.run("git push --tags")


def add_one_day(dt):
    return dt + datetime.timedelta(days=1)


def date_offset(dt, month_offset=0, day_offset=0, truncate=False):
    new_month = (dt.month + month_offset) % 12
    year_offset = new_month // 12
    replace_args = {
        "month": dt.month + month_offset,
        "year": dt.year + year_offset,
    }
    log(
        "Getting updated date from date: {} using month offset: {} and year offset {}".format(
            dt, new_month, replace_args["year"]
        )
    )
    if day_offset:
        dt = dt + datetime.timedelta(days=day_offset)
        log(f"updated date using day offset: {day_offset} => {dt}")
    if truncate:
        log("Truncating...")
        replace_args["day"] = 1
    return dt.replace(**replace_args)


@invoke.task
def bump_version(ctx, dry_run=False, pre=False, dev=False):
    current_version = semver.VersionInfo.parse(__version__)

    # Prompt the user for version change type
    while True:
        change_type = input("Enter the version change type (major/minor/patch): ").lower()
        if change_type in ["major", "minor", "patch"]:
            break
        print("Invalid input. Please enter 'major', 'minor', or 'patch'.")

    # Bump the version based on the user input
    if change_type == "major":
        new_version = current_version.bump_major()
    elif change_type == "minor":
        new_version = current_version.bump_minor()
    else:
        new_version = current_version.bump_patch()

    # Pre-release handling code
    if pre:
        new_version = new_version.bump_prerelease()
    if dev:
        new_version = new_version.bump_prerelease(current_version, "dev")

    # Update the version file
    log(f"Updating version to {new_version}")
    version = find_version(ctx)
    log(f"Found current version: {version}")
    if dry_run:
        log(f"Would update to: {new_version}")
    else:
        log(f"Updating to: {new_version}")
        version_file = get_version_file(ctx)
        file_contents = version_file.read_text()
        version_file.write_text(file_contents.replace(version, str(new_version)))
        ctx.run(f"git add {version_file.as_posix()}")
        log("Committing...")
        ctx.run(f'git commit -s -m "Bumped version to {new_version}."')
    return str(new_version)