-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoxfile.py
295 lines (230 loc) · 8.59 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
295
from __future__ import annotations
from contextlib import contextmanager
import importlib.util
import logging
import os
from pathlib import Path
import platform
import shutil
import typing as t
import nox
## Set nox options
if importlib.util.find_spec("uv"):
nox.options.default_venv_backend = "uv|virtualenv"
else:
nox.options.default_venv_backend = "virtualenv"
nox.options.reuse_existing_virtualenvs = True
nox.options.error_on_external_run = False
nox.options.error_on_missing_interpreters = False
# nox.options.report = True
## Define sessions to run when no session is specified
nox.sessions = ["ruff-lint", "export"]
## Create logger for this module
log: logging.Logger = logging.getLogger("nox")
## Define versions to test
PY_VERSIONS: list[str] = ["3.12", "3.11"]
## Get tuple of Python ver ('maj', 'min', 'mic')
PY_VER_TUPLE: tuple[str, str, str] = platform.python_version_tuple()
## Dynamically set Python version
DEFAULT_PYTHON: str = f"{PY_VER_TUPLE[0]}.{PY_VER_TUPLE[1]}"
## Set directory for requirements.txt file output
REQUIREMENTS_OUTPUT_DIR: Path = Path(".")
# this VENV_DIR constant specifies the name of the dir that the `dev`
# session will create, containing the virtualenv;
# the `resolve()` makes it portable
VENV_DIR = Path("./.venv").resolve()
LINT_PATHS: list[str] = [
"src",
"packages",
"applications",
"scripts",
"libs",
"sandbox",
]
def install_uv_project(session: nox.Session, external: bool = False) -> None:
"""Method to install uv and the current project in a nox session."""
log.info("Installing uv in session")
session.install("uv")
log.info("Syncing uv project")
session.run("uv", "sync", external=external)
log.info("Installing project")
session.run("uv", "pip", "install", ".", external=external)
@contextmanager
def cd(new_dir) -> t.Generator[None, t.Any, None]: # type: ignore
"""Context manager to change a directory before executing command."""
prev_dir: str = os.getcwd()
os.chdir(os.path.expanduser(new_dir))
try:
yield
finally:
os.chdir(prev_dir)
@nox.session(name="dev-env", tags=["setup"])
def dev(session: nox.Session) -> None:
"""Sets up a python development environment for the project.
Run this on a fresh clone of the repository to automate building the project with uv.
"""
install_uv_project(session, external=True)
@nox.session(python=[DEFAULT_PYTHON], name="ruff-lint", tags=["ruff", "clean", "lint"])
def run_linter(session: nox.Session, lint_paths: list[str] = LINT_PATHS):
"""Nox session to run Ruff code linting."""
if not Path("ruff.toml").exists():
if not Path("pyproject.toml").exists():
log.warning(
"""No ruff.toml file found. Make sure your pyproject.toml has a [tool.ruff] section!
If your pyproject.toml does not have a [tool.ruff] section, ruff's defaults will be used.
Double check imports in _init_.py files, ruff removes unused imports by default.
"""
)
session.install("ruff")
log.info("Linting code")
for d in lint_paths:
if not Path(d).exists():
log.warning(f"Skipping lint path '{d}', could not find path")
pass
else:
lint_path: Path = Path(d)
log.info(f"Running ruff imports sort on '{d}'")
session.run(
"ruff",
"check",
lint_path,
"--select",
"I",
"--fix",
)
log.info(f"Running ruff checks on '{d}' with --fix")
session.run(
"ruff",
"check",
lint_path,
"--fix",
)
## Find stray Python files not in src/, .venv/, or .nox/
all_python_files = [
f
for f in Path("./").rglob("*.py")
if ".venv" not in f.parts and ".nox" not in f.parts and "src" not in f.parts
]
log.info(f"Found [{len(all_python_files)}] Python file(s) to lint")
for py_file in all_python_files:
log.info(f"Linting Python file: {py_file}")
session.run("ruff", "check", str(py_file), "--fix")
@nox.session(python=[DEFAULT_PYTHON], name="vulture-check", tags=["quality"])
def run_vulture_check(session: nox.Session):
session.install(f"vulture")
log.info("Checking for dead code with vulture")
session.run("vulture", "src/", "--min-confidence", "100")
session.run("vulture", "libs/", "--min-confidence", "100")
session.run("vulture", "sandbox/", "--min-confidence", "100")
session.run("vulture", "scripts/", "--min-confidence", "100")
@nox.session(python=[DEFAULT_PYTHON], name="uv-export")
@nox.parametrize("requirements_output_dir", REQUIREMENTS_OUTPUT_DIR)
def export_requirements(session: nox.Session, requirements_output_dir: Path):
## Ensure REQUIREMENTS_OUTPUT_DIR path exists
if not requirements_output_dir.exists():
try:
requirements_output_dir.mkdir(parents=True, exist_ok=True)
except Exception as exc:
msg = Exception(
f"Unable to create requirements export directory: '{requirements_output_dir}'. Details: {exc}"
)
log.error(msg)
requirements_output_dir: Path = Path("./")
session.install(f"uv")
log.info("Exporting production requirements")
session.run(
"uv",
"export",
"--no-hashes",
"-o",
str(REQUIREMENTS_OUTPUT_DIR / "requirements.txt"),
)
log.info("Exporting development requirements")
session.run(
"uv",
"export",
"--only-dev",
"--no-hashes",
str(REQUIREMENTS_OUTPUT_DIR / "requirements.dev.txt"),
)
## Run pytest with xdist, allowing concurrent tests
@nox.session(python=DEFAULT_PYTHON, name="tests")
def run_tests(session: nox.Session):
install_uv_project(session)
session.install("pytest-xdist")
print("Running Pytest tests")
session.run(
"uv",
"run",
"pytest",
"-n",
"auto",
"--tb=auto",
"-v",
"-rsXxfP",
)
@nox.session(name="init-clone-setup")
def run_init_clone_setup(session: nox.Session):
install_uv_project(session)
copy_paths = [
{"src": "./config/settings.toml", "dest": "./config/settings.local.toml"},
{"src": "./config/.secrets.toml", "dest": "./config/.secrets.local.toml"},
]
for p in copy_paths:
if not Path(p["dest"]).exists():
log.info(f"Copying {p['src']} to {p['dest']}")
shutil.copyfile(p["src"], p["dest"])
else:
log.info(f"{p['dest']} already exists, skipping copy")
###########
# Alembic #
###########
@nox.session(python=[DEFAULT_PYTHON], name="alembic-migrate", tags=["alembic", "db"])
def run_alembic_migrations(session: nox.Session):
# session.install("alembic")
install_uv_project(session)
log.info("Running database migrations with alembic")
session.run(
"alembic", "revision", "--autogenerate", "-m", "'autogenerated migration'"
)
session.run("alembic", "upgrade", "head")
@nox.session(python=[DEFAULT_PYTHON], name="alembic-upgrade", tags=["alembic", "db"])
def run_alembic_migrations(session: nox.Session):
# session.install("alembic")
install_uv_project(session)
revision = input("Revision to upgrade (default: 'head'): ") or "head"
log.info(f"Running alembic upgrade {revision}")
session.run("alembic", "upgrade", revision)
@nox.session(python=[DEFAULT_PYTHON], name="alembic-init", tags=["init"])
def run_alembic_initialization(session: nox.Session):
if Path("./alembic").exists():
log.warning("Migrations directory [./alembic] exists. Skipping alembic init.")
return
install_uv_project(session)
log.info("Initializing Alembic database")
session.run("alembic", "init", "migrations")
log.info(
"""
!! READ THIS !!
Alembic initialized at path ./migrations.
You must edit migrations/env.py to configure your project.
If you're using a "src" layout, add this to the top of your code:
import sys
sys.path.append("./src")
Import your SQLAlchemy models (look for the commented sections describing model imports),
set your SQLAlchemy Base.metadata, and set the database URI.
If you're using Dynaconf, i.e. in a `db.settings.DB_SETTINGS` object, you can set the
database URI like:
## Get database URI from config
# !! You have to write this function !!
DB_URI = get_db_uri()
## Set alembic's SQLAlchemy URL
if DB_URI:
config.set_main_option(
"sqlalchemy.url", DB_URI.render_as_string(hide_password=False)
)
else:
raise Exception("DATABASE_URL not found in Dynaconf settings")
!! READ THIS !!
"""
)