This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
283 lines (211 loc) · 7.03 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
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
"""
This project uses Invoke (pyinvoke.org) for task management.
Install it via:
```
pip install invoke
```
And then run:
```
inv --list
```
"""
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from invoke import Context, Result, task
def echo_header(msg: str):
print(f"\n--- {msg} ---")
@dataclass
class Emo:
DO = "🤖"
GOOD = "✅"
FAIL = "🚨"
WARN = "🚧"
SYNC = "🚂"
PY = "🐍"
CLEAN = "🧹"
TEST = "🧪"
COMMUNICATE = "📣"
def git_init(c: Context):
# If no .git directory exits
if not Path(".git").exists():
echo_header(f"{Emo.DO} Initializing Git repository")
c.run("git init")
c.run("git add .")
c.run("git commit -m 'Initial commit'")
print(f"{Emo.GOOD} Git repository initialized")
else:
print(f"{Emo.GOOD} Git repository already initialized")
def setup_venv(
c: Context,
python_version: str,
) -> str:
venv_name = f'.venv{python_version.replace(".", "")}'
if not Path(venv_name).exists():
echo_header(
f"{Emo.DO} Creating virtual environment for {Emo.PY}{python_version}",
)
c.run(f"python{python_version} -m venv {venv_name}")
print(f"{Emo.GOOD} Virtual environment created")
else:
print(f"{Emo.GOOD} Virtual environment already exists")
c.run(f"source {venv_name}/bin/activate")
return venv_name
def _add_commit(c: Context, msg: Optional[str] = None):
print("🔨 Adding and committing changes")
c.run("git add .")
if msg is None:
msg = input("Commit message: ")
c.run(f'git commit -m "{msg}"', pty=True, hide=True)
print("\n🤖 Changes added and committed\n")
def is_uncommitted_changes(c: Context) -> bool:
git_status_result: Result = c.run(
"git status --porcelain",
pty=True,
hide=True,
)
uncommitted_changes = git_status_result.stdout != ""
return uncommitted_changes
def add_and_commit(c: Context, msg: Optional[str] = None):
"""Add and commit all changes."""
if is_uncommitted_changes(c):
uncommitted_changes_descr = c.run(
"git status --porcelain",
pty=True,
hide=True,
).stdout
echo_header(
f"{Emo.WARN} Uncommitted changes detected",
)
for line in uncommitted_changes_descr.splitlines():
print(f" {line.strip()}")
print("\n")
_add_commit(c, msg=msg)
def branch_exists_on_remote(c: Context) -> bool:
branch_name = Path(".git/HEAD").read_text().split("/")[-1].strip()
branch_exists_result: Result = c.run(
f"git ls-remote --heads origin {branch_name}",
hide=True,
)
return branch_name in branch_exists_result.stdout
def update_branch(c: Context):
echo_header(f"{Emo.SYNC} Syncing branch with remote")
if not branch_exists_on_remote(c):
c.run("git push --set-upstream origin HEAD")
else:
print("Pulling")
c.run("git pull")
print("Pushing")
c.run("git push")
def create_pr(c: Context):
c.run(
"gh pr create --web",
pty=True,
)
def update_pr(c: Context):
echo_header(f"{Emo.COMMUNICATE} Syncing PR")
# Get current branch name
branch_name = Path(".git/HEAD").read_text().split("/")[-1].strip()
pr_result: Result = c.run(
"gh pr list --state OPEN",
pty=False,
hide=True,
)
if branch_name not in pr_result.stdout:
create_pr(c)
else:
open_web = input("Open in browser? [y/n] ")
if "y" in open_web.lower():
c.run("gh pr view --web", pty=True)
def exit_if_error_in_stdout(result: Result):
# Find N remaining using regex
if "error" in result.stdout:
errors_remaining = re.findall(r"\d+(?=( remaining))", result.stdout)[
0
] # testing
if errors_remaining != "0":
exit(0)
def pre_commit(c: Context):
"""Run pre-commit checks."""
# Essential to have a clean working directory before pre-commit to avoid committing
# heterogenous files under a "style: linting" commit
if is_uncommitted_changes(c):
print(
f"{Emo.WARN} Your git working directory is not clean. Stash or commit before running pre-commit.",
)
exit(0)
echo_header(f"{Emo.CLEAN} Running pre-commit checks")
pre_commit_cmd = "pre-commit run --all-files"
result = c.run(pre_commit_cmd, pty=True, warn=True)
exit_if_error_in_stdout(result)
if "fixed" in result.stdout or "reformatted" in result.stdout:
_add_commit(c, msg="style: linting")
print(f"{Emo.DO} Fixed errors, re-running pre-commit checks")
second_result = c.run(pre_commit_cmd, pty=True, warn=True)
exit_if_error_in_stdout(second_result)
def mypy(c: Context):
echo_header(f"{Emo.CLEAN} Running mypy")
c.run("mypy .", pty=True)
@task
def install(c: Context):
echo_header(f"{Emo.DO} Installing project")
c.run("pip install -e '.[dev,tests]'")
@task
def setup(c: Context, python_version: str = "3.9"):
git_init(c)
venv_name = setup_venv(c, python_version=python_version)
print(
f"{Emo.DO} Activate your virtual environment by running: \n\n\t\t source {venv_name}/bin/activate \n",
)
print(f"{Emo.DO} Then install the project by running: \n\n\t\t inv install\n")
@task
def update(c: Context):
echo_header(f"{Emo.DO} Updating project")
c.run("pip install --upgrade -e '.[dev,tests]'")
@task
def test(c: Context):
echo_header(f"{Emo.TEST} Running tests")
test_result: Result = c.run(
"pytest -n auto -rfE --failed-first -p no:typeguard -p no:cov --disable-warnings -q",
warn=True,
pty=True,
)
# If "failed" in the pytest results
if "failed" in test_result.stdout:
print("\n\n\n")
echo_header("Failed tests")
# Get lines with "FAILED" in them from the .pytest_results file
failed_tests = [
line
for line in Path("tests/.pytest_results").read_text().splitlines()
if line.startswith("FAILED")
]
for line in failed_tests:
# Remove from start of line until /test_
line_sans_prefix = line[line.find("test_") :]
# Keep only that after ::
line_sans_suffix = line_sans_prefix[line_sans_prefix.find("::") + 2 :]
print(f"FAILED {Emo.FAIL} #{line_sans_suffix} ")
if test_result.return_code != 0:
exit(0)
def test_for_rej(c: Context):
# Check if any file in current directory, or its subdirectories, has a .rej extension
# If so, exit
rej_files = c.run("find . -name '*.rej' -type f -print", hide=True)
if ".rej" in rej_files.stdout:
print(f"\n{Emo.FAIL} Found .rej files leftover from cruft update.")
print(f"{rej_files.stdout}")
exit(0)
@task
def lint(c: Context):
test_for_rej(c)
pre_commit(c)
mypy(c)
@task
def pr(c: Context):
add_and_commit(c)
lint(c)
test(c)
update_branch(c)
update_pr(c)