-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
207 lines (151 loc) · 5.67 KB
/
tasks.py
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
"""Everything here is shamelessly copied from https://github.com/compas-dev/compas_invocations2"""
import sys
import glob
import os
import shutil
import contextlib
import invoke
HERE = os.path.dirname(__file__)
# NOTE: originally taken from invocations https://github.com/pyinvoke/invocations/blob/main/invocations/console.py
def confirm(question, assume_yes=True):
"""
Ask user a yes/no question and return their response as a boolean.
``question`` should be a simple, grammatically complete question such as
"Do you wish to continue?", and will have a string similar to ``" [Y/n] "``
appended automatically. This function will *not* append a question mark for
you.
By default, when the user presses Enter without typing anything, "yes" is
assumed. This can be changed by specifying ``assume_yes=False``.
.. note::
If the user does not supply input that is (case-insensitively) equal to
"y", "yes", "n" or "no", they will be re-prompted until they do.
Parameters
----------
question : str
The question part of the prompt.
assume_yes : bool
Whether to assume the affirmative answer by default. Defaults to ``True``.
Returns
-------
bool
"""
if assume_yes:
suffix = "Y/n"
else:
suffix = "y/N"
while True:
response = input("{} [{}] ".format(question, suffix))
response = response.lower().strip()
if not response:
return assume_yes
if response in ["y", "yes"]:
return True
if response in ["n", "no"]:
return False
err = "Focus, kid! It is either (y)es or (n)o"
print(err, file=sys.stderr)
@contextlib.contextmanager
def chdir(dirname=None):
"""Context-manager syntax to change to a directory and return to the current one afterwards."""
current_dir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(current_dir)
@invoke.task()
def lint(ctx):
"""Check the consistency of coding style."""
print("\nRunning ruff linter...")
ctx.run("ruff check --fix src tests")
print("\nRunning black linter...")
ctx.run("black --check --diff --color src tests")
print("\nAll linting is done!")
@invoke.task()
def format(ctx):
"""Reformat the code base using black."""
print("\nRunning ruff formatter...")
ctx.run("ruff format src tests")
print("\nRunning black formatter...")
ctx.run("black src tests")
print("\nAll formatting is done!")
@invoke.task()
def check(ctx):
"""Check the consistency of documentation, coding style and a few other things."""
with chdir(HERE):
lint(ctx)
@invoke.task(
help={
"docs": "True to clean up generated documentation, otherwise False",
"bytecode": "True to clean up compiled python files, otherwise False.",
"builds": "True to clean up build/packaging artifacts, otherwise False.",
}
)
def clean(ctx, docs=True, bytecode=True, builds=True):
"""Cleans the local copy from compiled artifacts."""
with chdir(HERE):
if bytecode:
for root, dirs, files in os.walk(HERE):
for f in files:
if f.endswith(".pyc"):
os.remove(os.path.join(root, f))
if ".git" in dirs:
dirs.remove(".git")
folders = []
if docs:
folders.append("docs/api/generated")
folders.append("dist/")
if bytecode:
for t in ("src", "tests"):
folders.extend(glob.glob("{}/**/__pycache__".format(t), recursive=True))
if builds:
folders.append("build/")
folders.extend(glob.glob("src/**/*.egg-info", recursive=False))
for folder in folders:
shutil.rmtree(os.path.join(HERE, folder), ignore_errors=True)
@invoke.task(help={"release_type": "Type of release follows semver rules. Must be one of: major, minor, patch."})
def release(ctx, release_type):
"""Releases the project in one swift command!"""
if release_type not in ("patch", "minor", "major"):
raise invoke.Exit("The release type parameter is invalid.\nMust be one of: major, minor, patch.")
# Run formatter
ctx.run("invoke format")
# Run checks
ctx.run("invoke test")
# Bump version and git tag it
ctx.run("bump-my-version bump %s --verbose" % release_type)
# Build project
ctx.run("python -m build")
# Prepare the change log for the next release
prepare_changelog(ctx)
# Clean up local artifacts
clean(ctx)
# Upload to pypi
if confirm(
"Everything is ready. You are about to push to git which will trigger a release to pypi.org. Are you sure?",
assume_yes=False,
):
ctx.run("git push --tags && git push")
else:
raise invoke.Exit("You need to manually revert the tag/commits created.")
@invoke.task
def prepare_changelog(ctx):
"""Prepare changelog for next release."""
UNRELEASED_CHANGELOG_TEMPLATE = "## Unreleased\n\n### Added\n\n### Changed\n\n### Removed\n\n\n## "
with chdir(HERE):
# Preparing changelog for next release
with open("CHANGELOG.md", "r+") as changelog:
content = changelog.read()
changelog.seek(0)
changelog.write(content.replace("## ", UNRELEASED_CHANGELOG_TEMPLATE, 1))
ctx.run('git add CHANGELOG.md && git commit -m "Prepare changelog for next release"')
@invoke.task
def test(ctx):
"""Run tests."""
ctx.run("pytest")
@invoke.task
def docs(ctx):
"""Build the documentation."""
with chdir(HERE):
ctx.run("sphinx-build -b html docs docs/_build")