Repository navigation
Expand file tree
/
Copy pathcheck_setup.py
More file actions
396 lines (325 loc) · 12.2 KB
/
Copy pathcheck_setup.py
File metadata and controls
396 lines (325 loc) · 12.2 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env python3
"""check_setup.py - verify your machine is ready to work through this course.
Run it from the project root:
python check_setup.py
It checks every prerequisite described in SETUP.md and, for anything missing,
prints the exact command to fix it *for your operating system*. Nothing is
installed or modified - this script only looks.
Written in deliberately old-fashioned Python (no modern syntax, standard library
only) so that it still runs and gives you a helpful message even when your Python
is too old or the project's dependencies are not installed yet.
"""
import os
import platform
import shutil
import subprocess
import sys
# --- Minimum Python for this project (modern type-hint syntax needs 3.10) ----
MIN_PYTHON = (3, 10)
# --- Tiny terminal colour helpers -------------------------------------------
# Windows terminals older than Windows 10 don't understand ANSI colour codes, and
# piping output to a file shouldn't include them either, so we degrade to plain
# text whenever we're not attached to a real terminal.
def _supports_colour():
if not hasattr(sys.stdout, "isatty") or not sys.stdout.isatty():
return False
if os.environ.get("NO_COLOR"):
return False
return True
COLOUR = _supports_colour()
def paint(text, code):
if not COLOUR:
return text
return "\033[" + code + "m" + text + "\033[0m"
def green(t):
return paint(t, "32")
def red(t):
return paint(t, "31")
def yellow(t):
return paint(t, "33")
def bold(t):
return paint(t, "1")
OK = green("PASS")
FAIL = red("MISSING")
WARN = yellow("OPTIONAL")
# --- Results collected as we go ---------------------------------------------
problems = [] # things that block you
warnings = [] # things you only need for later chapters
def record(kind, message, fix):
if kind == "problem":
problems.append((message, fix))
else:
warnings.append((message, fix))
def line(status, label, detail):
print(" " + status.ljust(18) + label.ljust(22) + detail)
def run(cmd):
"""Run a command and return its first line of output, or None if it fails."""
try:
out = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=15,
)
except (OSError, subprocess.SubprocessError):
return None
if out.returncode != 0:
return None
text = out.stdout.decode("utf-8", "replace").strip()
if not text:
return ""
return text.splitlines()[0].strip()
# --- Which OS are we on? Used to print the right install command -------------
SYSTEM = platform.system() # 'Darwin', 'Windows', or 'Linux'
IS_MAC = SYSTEM == "Darwin"
IS_WINDOWS = SYSTEM == "Windows"
IS_LINUX = SYSTEM == "Linux"
OS_LABEL = {"Darwin": "macOS", "Windows": "Windows", "Linux": "Linux"}.get(
SYSTEM, SYSTEM
)
def install_hint(mac, windows, linux):
"""Pick the install instruction matching the current OS."""
if IS_MAC:
return mac
if IS_WINDOWS:
return windows
if IS_LINUX:
return linux
return mac
# ===========================================================================
# Checks
# ===========================================================================
def check_python():
print(bold("\nPython"))
version = sys.version_info
shown = "%d.%d.%d" % (version[0], version[1], version[2])
need = "%d.%d" % MIN_PYTHON
if version >= MIN_PYTHON:
line(OK, "python", shown)
else:
line(FAIL, "python", shown + " (need " + need + " or newer)")
record(
"problem",
"Python " + shown + " is too old; this project needs " + need + "+",
install_hint(
"brew install python@3.12 (or download from python.org)",
"winget install Python.Python.3.12",
"sudo apt install python3 (or use pyenv / deadsnakes)",
),
)
# Are we inside a virtual environment? sys.prefix differs from
# sys.base_prefix exactly when a venv is active.
in_venv = sys.prefix != getattr(sys, "base_prefix", sys.prefix)
if in_venv:
line(OK, "virtualenv", "active -> " + sys.prefix)
else:
line(FAIL, "virtualenv", "NOT active (you are using the system Python)")
record(
"problem",
"Virtual environment is not active",
install_hint(
"python3 -m venv .venv && source .venv/bin/activate",
"py -3 -m venv .venv; .venv\\Scripts\\Activate.ps1",
"python3 -m venv .venv && source .venv/bin/activate",
),
)
return in_venv
def check_python_packages(in_venv):
"""Confirm the pip dependencies from requirements.txt are importable."""
print(bold("\nPython packages (from requirements.txt)"))
# (import name, what it is)
required = [
("fastapi", "the web framework"),
("uvicorn", "the server that runs it"),
("sqlalchemy", "the ORM / database toolkit"),
("alembic", "database migrations"),
("pydantic", "validation"),
("pydantic_settings", "config from .env"),
("passlib", "password hashing"),
("jose", "JWT tokens"),
("multipart", "form/login parsing"),
("pytest", "test runner"),
("httpx", "test HTTP client"),
("reportlab", "builds the course PDF"),
]
missing = []
for module_name, purpose in required:
try:
__import__(module_name)
line(OK, module_name, purpose)
except ImportError:
line(FAIL, module_name, purpose)
missing.append(module_name)
if missing:
hint = "pip install -r requirements.txt"
if not in_venv:
hint = "Activate the venv first, then: " + hint
record(
"problem",
str(len(missing)) + " Python package(s) not installed: "
+ ", ".join(missing),
hint,
)
def check_sqlite():
print(bold("\nSQLite"))
# Python's own sqlite3 module - needed by the app itself.
try:
import sqlite3 as _sqlite3
line(OK, "python sqlite3", "library version " + _sqlite3.sqlite_version)
except ImportError:
line(FAIL, "python sqlite3", "Python built without SQLite support")
record(
"problem",
"Python's built-in sqlite3 module is unavailable",
install_hint(
"brew install python@3.12 (reinstall Python)",
"Reinstall Python from python.org",
"sudo apt install libsqlite3-dev, then reinstall Python",
),
)
# The separate command-line tool - needed to type SQL by hand in Ch 4-6.
if shutil.which("sqlite3"):
version = run(["sqlite3", "--version"]) or "installed"
line(OK, "sqlite3 CLI", version.split(" ")[0])
else:
line(FAIL, "sqlite3 CLI", "not found on PATH (needed for Ch 4-6)")
record(
"problem",
"The sqlite3 command-line tool is not installed",
install_hint(
"It ships with macOS - check your PATH",
"winget install SQLite.SQLite",
"sudo apt install sqlite3",
),
)
def check_node():
print(bold("\nNode.js (for the React frontend, Ch 15-16)"))
if shutil.which("node"):
line(OK, "node", run(["node", "--version"]) or "installed")
else:
line(WARN, "node", "not found (only needed from Ch 15)")
record(
"warning",
"Node.js is not installed (needed for the React frontend in Ch 15)",
install_hint(
"brew install node",
"winget install OpenJS.NodeJS.LTS",
"sudo apt install nodejs npm (or use nvm)",
),
)
if shutil.which("npm"):
line(OK, "npm", run(["npm", "--version"]) or "installed")
elif shutil.which("node"):
line(WARN, "npm", "not found although node is installed")
def check_optional_tools():
print(bold("\nOther tools"))
# Git - not required to run anything, but you should version your work.
if shutil.which("git"):
line(OK, "git", run(["git", "--version"]) or "installed")
else:
line(WARN, "git", "not found (recommended, to track your work)")
record(
"warning",
"Git is not installed (recommended so you can track your progress)",
install_hint(
"brew install git",
"winget install Git.Git",
"sudo apt install git",
),
)
# PostgreSQL - only Chapter 14.
if shutil.which("psql"):
line(OK, "psql", run(["psql", "--version"]) or "installed")
else:
line(WARN, "psql", "not found (only needed for Ch 14)")
record(
"warning",
"PostgreSQL is not installed (only needed in Ch 14)",
install_hint(
"brew install postgresql@16 (or use Postgres.app)",
"winget install PostgreSQL.PostgreSQL.16",
"sudo apt install postgresql",
),
)
# Docker - only Chapter 16, and optional even there.
if shutil.which("docker"):
line(OK, "docker", run(["docker", "--version"]) or "installed")
else:
line(WARN, "docker", "not found (optional, Ch 16)")
record(
"warning",
"Docker is not installed (optional, used in Ch 16)",
"Install Docker Desktop from docker.com",
)
def check_project_files():
"""Make sure we're actually being run from the project root."""
print(bold("\nProject files"))
here = os.path.dirname(os.path.abspath(__file__))
# (label shown, path to check, what it is)
expected = [
("requirements.txt", "requirements.txt", "the Python dependency list"),
("README.md", "README.md", "the project overview"),
("docs/", os.path.join("docs", "build_pdf.py"), "the PDF generator"),
(
"app/backend/",
os.path.join("app", "backend", "app", "main.py"),
"the FastAPI app",
),
(
"app/frontend/",
os.path.join("app", "frontend", "package.json"),
"the React app",
),
(
"chapters/",
os.path.join("chapters", "ch04_sql_foundations", "schema.sql"),
"the database schema",
),
]
missing = 0
for label, relative, purpose in expected:
if os.path.exists(os.path.join(here, relative)):
line(OK, label, purpose)
else:
line(FAIL, label, "missing " + relative)
missing += 1
if missing:
record(
"problem",
"Some project files are missing - are you in the right folder?",
"cd into the python-backend folder and run this script again",
)
def main():
print(bold("\n" + "=" * 66))
print(bold(" python-backend - setup check"))
print(bold("=" * 66))
print(" Operating system: " + OS_LABEL + " (" + platform.machine() + ")")
print(" Working directory: " + os.getcwd())
in_venv = check_python()
check_python_packages(in_venv)
check_sqlite()
check_node()
check_optional_tools()
check_project_files()
# ---- Summary -----------------------------------------------------------
print(bold("\n" + "=" * 66))
if not problems and not warnings:
print(green(bold(" Everything is ready. Open the PDF and start Chapter 1.")))
print(bold("=" * 66) + "\n")
return 0
if problems:
print(red(bold(" MUST FIX (" + str(len(problems)) + ")")))
for index, (message, fix) in enumerate(problems, 1):
print(" " + str(index) + ". " + message)
print(" fix: " + bold(fix))
if warnings:
print(yellow(bold("\n NOT YET NEEDED (" + str(len(warnings)) + ")")))
for index, (message, fix) in enumerate(warnings, 1):
print(" " + str(index) + ". " + message)
print(" fix: " + fix)
print(bold("\n Full instructions: SETUP.md"))
print(bold("=" * 66) + "\n")
# Exit non-zero only for real blockers, so this can be used in a script.
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())