- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtasks.py
More file actions
Latest commit
221 lines (177 loc) · 7.29 KB
/
Copy pathtasks.py
File metadata and controls
221 lines (177 loc) · 7.29 KB
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
"""
Assumptions:
* the project is structured as <name>/<name'> where <name>
is the project name and <name'> is the same as <name> except with any "-"
replaced by "_". `tasks.py` should be stored in <name>.
If you cloned this from gh:neighthan/cookiecutter-pytemplate, the structure is right.
"""
importre
importshutil
importsys
importjson
importtoml
importinvoke
frompathlibimportPath
fromtimeimportsleep
fromtypingimportSequence
fromurllib.requestimporturlopen
fromurllib.parseimportquote
frominvoke.exceptionsimportUnexpectedExit
_version_pattern=re.compile(
r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<micro>\d+)(\.(?P<suffix>[A-z0-9]+))?"
)
_index_url="--index-url https://test.pypi.org/simple"
_extra_url="--extra-index-url https://pypi.org/simple"# for dependencies
@invoke.task
defclean(ctx) ->None:
"""
Remove all temporary files and directories.
Files / directories removed are:
* __pycache__ directories
* .coverage files
* build and dist directories
"""
root_dir=Path(__file__).parent
rm_file_patterns= [".coverage"]
forfile_patterninrm_file_patterns:
forrm_fileinroot_dir.rglob(file_pattern):
rm_file.unlink()
rm_dir_patterns= ["__pycache__", "build", "dist"]
fordir_patterninrm_dir_patterns:
forrm_dirinroot_dir.rglob(dir_pattern):
shutil.rmtree(str(rm_dir))
@invoke.task(clean, post=[clean])
defpublish(
ctx, test: bool=False, install: bool=False, n_download_tries: int=3
) ->None:
"""
Publish the project to pypi / testpypi.
If you use the test flag, you have at least the following in `~/.pypirc`:
[testpypi]
repository: https://test.pypi.org/legacy/
:param ctx: invoke context
:param test: whether to publish to normal or test pypi. If publishing to testpypi,
.dev<dev_num> is added to the version where <dev_num> is one larger than the
highest dev version published. This is because testpypi won't let you publish the
same version multiple times; doing this automates changing the version for repeat
publishing + testing.
Additionally, the micro/patch version is incremented because it's assumed that
it's a dev version of the _next_ release.
WARNING - don't publish multiple times too quickly. If so, the next dev num
can't be pulled from testpypi because it won't have updated yet.
:param install: whether to install the project from test pypi.
Only used if `test` is true. This is better than running `invoke install`
separately because it will try multiple times to get the newly uploaded version
(it usually takes a couple of tries).
:param n_download_tries: how many times to attempt to install the project.
After each attempt there is a 5 second sleep period.
"""
project_name=_get_from_pyproject(["tool", "poetry", "name"])
project_root=str(Path(__file__).parent.resolve())
sleep_time=5
iftest:
pyproject_path=Path(__file__).parent/"pyproject.toml"
original_pyproject_str=pyproject_path.read_text()
pyproject=toml.loads(original_pyproject_str)
original_version=pyproject["tool"]["poetry"]["version"]
version=re.fullmatch(_version_pattern, original_version)
groups=version.groupdict()
major, minor, micro=groups["major"], groups["minor"], groups["micro"]
version=f"{major}.{minor}.{int(micro) +1}"
dev_num=_get_next_dev_num(project_name, version)
version+=f".dev{dev_num}"
# write back the modified version
pyproject["tool"]["poetry"]["version"] =version
pyproject_path.write_text(toml.dumps(pyproject))
try:
cmd=f"""
cd "{project_root}"
poetry build
twine upload {'--repository testpypi'iftestelse''} dist/*
"""
ctx.run(cmd)
finally:
iftest:
pyproject_path.write_text(original_pyproject_str)
ifnottestornotinstall:
return
foriinrange(n_download_tries):
sleep(sleep_time)
try:
result=ctx.run(
f"pip install {_index_url}{_extra_url}{project_name}=={version}"
)
break
exceptUnexpectedExit:
continue
@invoke.task
defupdate_tasks(ctx) ->None:
"""
Update the tasks file to the newest version on GitHub.
:param ctx: invoke context
"""
tasks_path=Path(__file__).resolve()
github_url="https://raw.githubusercontent.com/neighthan/cookiecutter-pytemplate/"
github_url+=quote("master/{{cookiecutter.project_name}}/tasks.py")
withurlopen(github_url) asnew_tasks_file:
tasks_path.write_text(new_tasks_file.read().decode())
@invoke.task
definstall(ctx, version: str="", test: bool=False) ->None:
"""
Install the latest version of the current project.
:param ctx: `invoke` context
:param test: whether to install from test pypi;
if so, `--pre` is used to allow dev versions
"""
project_name=_get_from_pyproject(["tool", "poetry", "name"])
cmd="pip install -U {} "+project_name+f"=={version}"ifversionelse""
cmd=cmd.format(" ".join([_index_url, _extra_url, "--pre"]) iftestelse"")
ctx.run(cmd)
@invoke.task(clean, allow_unknown=True)
deftest(ctx) ->None:
pytest_args=sys.argv[sys.argv.index("test") +1 :]
fori, arginenumerate(pytest_args):
if" "inarg:
pytest_args[i] =f'"{arg}"'
cmd="poetry run pytest "+" ".join(pytest_args)
ctx.run(cmd, pty=True)
@invoke.task
definstall_jupyter_kernel(ctx, name: str, install_prefix: str="") ->None:
"""
:param name: name for the kernel
:param install_prefix: default = ~/.local
"""
install_prefix=Path.home() /".local"
cmd=f'poetry run python -m ipykernel install --prefix={install_prefix} --name "{name}"'
ctx.run(cmd)
def_get_next_dev_num(project_name: str, current_version: str) ->int:
"""
Get 1 + the number of the latest dev version matching `current_version` w/o suffix.
To determine next dev_num we run pip and find the latest version that has the same
major.minor.micro as `current_version` and dev in the suffix, then we increment.
"""
cmd=f"pip install {_index_url}{project_name}==?"
result=invoke.run(cmd, warn=True, hide=True)
current_version=re.fullmatch(_version_pattern, current_version)
current_version_groups=current_version.groupdict()
dev_num=0
# reverse so that we hit the latest version first
forpublished_versioninlist(re.finditer(_version_pattern, result.stderr))[::-1]:
groups=published_version.groupdict()
if (
groups["major"] ==current_version_groups["major"]
andgroups["minor"] ==current_version_groups["minor"]
andgroups["micro"] ==current_version_groups["micro"]
andgroups["suffix"]
andgroups["suffix"].startswith("dev")
):
dev_num=int(groups["suffix"].replace("dev", "")) +1
break
returndev_num
def_get_from_pyproject(keys: Sequence[str]):
pyproject=Path(__file__).parent/"pyproject.toml"
pyproject=toml.loads(pyproject.read_text())
ret=pyproject
forkeyinkeys:
ret=ret[key]
returnret