forked from microsoft/vscode-mypy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
noxfile.py
294 lines (230 loc) · 9.81 KB
/
noxfile.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
284
285
286
287
288
289
290
291
292
293
294
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""All the action we need during build"""
import io
import json
import os
import pathlib
import re
import urllib.request as url_lib
import zipfile
from typing import List
import nox # pylint: disable=import-error
def _install_bundle(session: nox.Session) -> None:
session.install(
"-t",
"./bundled/libs",
"--no-cache-dir",
"--implementation",
"py",
"--no-deps",
"--upgrade",
"-r",
"./requirements.txt",
)
def _check_files(names: List[str]) -> None:
root_dir = pathlib.Path(__file__).parent
for name in names:
file_path = root_dir / name
lines: List[str] = file_path.read_text().splitlines()
if any(line for line in lines if line.startswith("# TODO:")):
raise ValueError(f"Please update {os.fspath(file_path)}.")
def _update_pip_packages(session: nox.Session) -> None:
session.run(
"pip-compile",
"--generate-hashes",
"--resolver=backtracking",
"--upgrade",
"./requirements.in",
)
session.run(
"pip-compile",
"--generate-hashes",
"--resolver=backtracking",
"--upgrade",
"./src/test/python_tests/requirements.in",
)
session.run(
"pip-compile",
"--generate-hashes",
"--resolver=backtracking",
"--upgrade",
"./dev_requirements.in",
)
def _get_package_data(package):
json_uri = f"https://registry.npmjs.org/{package}"
with url_lib.urlopen(json_uri) as response:
return json.loads(response.read())
def _update_npm_packages(session: nox.Session) -> None:
pinned = {
"vscode-languageclient",
"@types/vscode",
"@types/node",
}
package_json_path = pathlib.Path(__file__).parent / "package.json"
package_json = json.loads(package_json_path.read_text(encoding="utf-8"))
for package in package_json["dependencies"]:
if package not in pinned:
data = _get_package_data(package)
latest = "^" + data["dist-tags"]["latest"]
package_json["dependencies"][package] = latest
for package in package_json["devDependencies"]:
if package not in pinned:
data = _get_package_data(package)
latest = "^" + data["dist-tags"]["latest"]
package_json["devDependencies"][package] = latest
# Ensure engine matches the package
if (
package_json["engines"]["vscode"]
!= package_json["devDependencies"]["@types/vscode"]
):
print(
"Please check VS Code engine version and @types/vscode version in package.json."
)
new_package_json = json.dumps(package_json, indent=4)
# JSON dumps uses \n for line ending on all platforms by default
if not new_package_json.endswith("\n"):
new_package_json += "\n"
package_json_path.write_text(new_package_json, encoding="utf-8")
session.run("npm", "audit", "fix", external=True, success_codes=[0, 1])
session.run("npm", "install", external=True)
def _setup_template_environment(session: nox.Session) -> None:
session.install("wheel", "pip-tools")
_update_pip_packages(session)
_install_bundle(session)
session.run("npm", "install", external=True)
@nox.session(python="3.8")
def install_bundled_libs(session):
"""Installs the libraries that will be bundled with the extension."""
session.install("wheel")
_install_bundle(session)
@nox.session(python="3.8")
def setup(session: nox.Session) -> None:
"""Sets up the extension for development."""
_setup_template_environment(session)
@nox.session()
def tests(session: nox.Session) -> None:
"""Runs all the tests for the extension."""
session.install("-r", "src/test/python_tests/requirements.txt")
session.run("pytest", "--capture=no", "src/test/python_tests")
session.install("freezegun")
session.run("pytest", "build")
@nox.session()
def lint(session: nox.Session) -> None:
"""Runs linter and formatter checks on python files."""
session.install("-r", "./requirements.txt")
session.install("-r", "src/test/python_tests/requirements.txt")
session.install("flake8")
session.run("flake8", "./bundled/tool")
session.run(
"flake8",
"--extend-exclude",
"./src/test/python_tests/test_data",
"./src/test/python_tests",
)
session.run("flake8", "noxfile.py")
# check formatting using black
session.install("black")
session.run("black", "--check", "./bundled/tool")
session.run("black", "--check", "./src/test/python_tests")
session.run("black", "--check", "noxfile.py")
# check import sorting using isort
session.install("isort")
session.run("isort", "--check", "--profile", "black", "./bundled/tool")
session.run("isort", "--check", "--profile", "black", "./src/test/python_tests")
session.run("isort", "--check", "--profile", "black", "noxfile.py")
# check typescript code
session.run("npm", "run", "lint", external=True)
@nox.session()
def build_package(session: nox.Session) -> None:
"""Builds VSIX package for publishing."""
_check_files(["README.md", "LICENSE", "SECURITY.md", "SUPPORT.md"])
_setup_template_environment(session)
session.run("npm", "install", external=True)
session.run("npm", "run", "vsce-package", external=True)
@nox.session()
def update_build_number(session: nox.Session) -> None:
"""Updates build number for the extension."""
if len(session.posargs) == 0:
session.log("No updates to package version")
return
package_json_path = pathlib.Path(__file__).parent / "package.json"
session.log(f"Reading package.json at: {package_json_path}")
package_json = json.loads(package_json_path.read_text(encoding="utf-8"))
parts = re.split("\\.|-", package_json["version"])
major, minor = parts[:2]
version = f"{major}.{minor}.{session.posargs[0]}"
version = version if len(parts) == 3 else f"{version}-{''.join(parts[3:])}"
session.log(f"Updating version from {package_json['version']} to {version}")
package_json["version"] = version
package_json_path.write_text(json.dumps(package_json, indent=4), encoding="utf-8")
def _get_module_name() -> str:
package_json_path = pathlib.Path(__file__).parent / "package.json"
package_json = json.loads(package_json_path.read_text(encoding="utf-8"))
return package_json["serverInfo"]["module"]
@nox.session()
def validate_readme(session: nox.Session) -> None:
"""Ensures the linter version in 'requirements.txt' matches 'readme.md'."""
requirements_file = pathlib.Path(__file__).parent / "requirements.txt"
readme_file = pathlib.Path(__file__).parent / "README.md"
lines = requirements_file.read_text(encoding="utf-8").splitlines(keepends=False)
module = _get_module_name()
linter_ver = list(line for line in lines if line.startswith(module))[0]
name, version = linter_ver.split(" ")[0].split("==")
session.log(f"Looking for {name}={version} in README.md")
content = readme_file.read_text(encoding="utf-8")
if f"{name}={version}" not in content:
raise ValueError(f"Linter info {name}={version} was not found in README.md.")
session.log(f"FOUND {name}={version} in README.md")
def _update_readme() -> None:
requirements_file = pathlib.Path(__file__).parent / "requirements.txt"
lines = requirements_file.read_text(encoding="utf-8").splitlines(keepends=False)
module = _get_module_name()
linter_ver = list(line for line in lines if line.startswith(module))[0]
_, version = linter_ver.split(" ")[0].split("==")
readme_file = pathlib.Path(__file__).parent / "README.md"
content = readme_file.read_text(encoding="utf-8")
regex = r"\`([a-zA-Z0-9]+)=([0-9]+\.[0-9]+\.[0-9]+)\`"
result = re.sub(regex, f"`{module}={version}`", content, 0, re.MULTILINE)
readme_file.write_text(result, encoding="utf-8")
@nox.session()
def update_packages(session: nox.Session) -> None:
"""Update pip and npm packages."""
session.install("wheel", "pip-tools")
_update_pip_packages(session)
_update_npm_packages(session)
_update_readme()
def _contains(s, parts=()):
return any(p for p in parts if p in s)
def _get_pypi_package_data(package_name):
json_uri = "https://pypi.org/pypi/{0}/json".format(package_name)
# Response format: https://warehouse.readthedocs.io/api-reference/json/#project
# Release metadata format: https://github.com/pypa/interoperability-peps/blob/master/pep-0426-core-metadata.rst
with url_lib.urlopen(json_uri) as response:
return json.loads(response.read())
def _get_wheel_urls(data, version):
return list(
r["url"] for r in data["releases"][version] if _contains(r["url"], ("cp37",))
)
def _download_and_extract(root, url, version):
if "manylinux" in url or "macosx" in url or "win_amd64" in url:
root = os.getcwd() if root is None or root == "." else root
print(url)
with url_lib.urlopen(url) as response:
data = response.read()
with zipfile.ZipFile(io.BytesIO(data), "r") as wheel:
for zip_info in wheel.infolist():
# Ignore dist info since we are merging multiple wheels
if ".dist-info/" in zip_info.filename:
continue
print("\t" + zip_info.filename)
wheel.extract(zip_info.filename, root)
def _install_wheels(root, package_name, version="latest"):
from packaging.version import parse as version_parser
data = _get_pypi_package_data(package_name)
if version == "latest":
use_version = max(data["releases"].keys(), key=version_parser)
else:
use_version = version
for url in _get_wheel_urls(data, use_version):
_download_and_extract(root, url, use_version)