-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdev.py
More file actions
executable file
·2116 lines (1770 loc) · 85.1 KB
/
Copy pathdev.py
File metadata and controls
executable file
·2116 lines (1770 loc) · 85.1 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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
"""
LibreFolio Development CLI
Unified command-line interface for development tasks.
Supports autocompletion via argcomplete.
Usage:
./dev.py <command> [options]
python dev.py <command> [options]
Autocompletion setup:
# Add to ~/.bashrc or ~/.zshrc:
eval "$(register-python-argcomplete dev.py)"
"""
import argparse
import hashlib
import math
import os
import platform
import re
import secrets
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path
try:
import argcomplete
HAS_ARGCOMPLETE = True
except ImportError:
HAS_ARGCOMPLETE = False
# Ensure project root is in path
PROJECT_ROOT = Path(__file__).parent.resolve()
sys.path.insert(0, str(PROJECT_ROOT))
sys.path.insert(0, str(PROJECT_ROOT / "scripts"))
# Change to project root for consistent paths
os.chdir(PROJECT_ROOT)
from scripts.cli_base import (
Colors,
check_server_running,
get_data_dir,
get_database_path,
get_server_host,
get_server_port,
get_test_database_path,
get_test_server_port,
pipenv_prefix,
print_error,
print_header,
print_success,
print_warning,
run_command_live,
run_pipenv,
)
from scripts.cli_tree_parser import TreeParser, format_help
# =============================================================================
# Backend Commands: Server
# =============================================================================
def check_port_in_use(port: int) -> list:
"""Check if port is in use and return list of (PID, process_name) tuples."""
processes = []
try:
if platform.system() == "Darwin": # macOS
# Get PIDs first
result = subprocess.run(
["lsof", "-i", f":{port}", "-t"],
capture_output=True, text=True
)
if result.stdout.strip():
pids = [int(p) for p in result.stdout.strip().split('\n') if p]
# Get process name for each PID
for pid in pids:
try:
ps_result = subprocess.run(
["ps", "-p", str(pid), "-o", "comm="],
capture_output=True, text=True
)
proc_name = ps_result.stdout.strip() or "unknown"
processes.append((pid, proc_name))
except Exception:
processes.append((pid, "unknown"))
elif platform.system() == "Linux":
result = subprocess.run(
["fuser", f"{port}/tcp"],
capture_output=True, text=True, stderr=subprocess.DEVNULL
)
if result.stdout.strip():
pids = [int(p) for p in result.stdout.strip().split() if p]
for pid in pids:
try:
ps_result = subprocess.run(
["ps", "-p", str(pid), "-o", "comm="],
capture_output=True, text=True
)
proc_name = ps_result.stdout.strip() or "unknown"
processes.append((pid, proc_name))
except Exception:
processes.append((pid, "unknown"))
except Exception:
pass
return processes
def _print_port_help(port: int, processes: list):
"""Print help message for port-in-use errors."""
print()
print(f"{Colors.YELLOW}Processes using port {port}:{Colors.NC}")
pids = []
for pid, proc_name in processes:
pids.append(str(pid))
print(f" • PID {pid} ({proc_name})")
print()
print(f"{Colors.BLUE}To view details:{Colors.NC}")
print(f" lsof -i :{port}")
print()
print(f"{Colors.BLUE}To kill these processes:{Colors.NC}")
print(f" kill -9 {' '.join(pids)}")
print()
print(f"{Colors.YELLOW}Tip:{Colors.NC} This often happens when a previous server didn't shut down cleanly.")
print(f"{Colors.YELLOW} Use --force to automatically kill blocking processes.{Colors.NC}")
def cmd_server(args):
"""Start the development server."""
test_mode = getattr(args, 'test', False)
rebuild = getattr(args, 'rebuild', False)
debug_mode = getattr(args, 'debug', False)
force = getattr(args, 'force', False)
workers = getattr(args, 'workers', 1)
host_override = getattr(args, 'host', None)
port_override = getattr(args, 'port', None)
coverage_mode = getattr(args, 'coverage', False)
no_scheduler = getattr(args, 'no_scheduler', False)
if test_mode:
port = get_test_server_port()
db = get_database_path(test_mode=True)
debug_mode = True
else:
port = get_server_port()
db = get_database_path(test_mode=False)
# Apply --host / --port overrides (take priority over env vars)
host = host_override if host_override else get_server_host()
if port_override:
port = port_override
# Check if port is already in use
processes_using_port = check_port_in_use(port)
if processes_using_port:
if force:
# --force: kill blocking processes and continue
pids = [pid for pid, _ in processes_using_port]
print_warning(f"Port {port} is in use — killing {len(pids)} blocking process(es)...")
for pid, proc_name in processes_using_port:
try:
os.kill(pid, signal.SIGKILL)
print(f" ✗ Killed PID {pid} ({proc_name})")
except ProcessLookupError:
pass # already dead
except PermissionError:
print_error(f" Cannot kill PID {pid} ({proc_name}) — permission denied")
return 1
# Wait briefly for port to be released
time.sleep(1)
# Verify port is now free
still_in_use = check_port_in_use(port)
if still_in_use:
print_error(f"Port {port} still in use after killing processes!")
_print_port_help(port, still_in_use)
return 1
print_success(f"Port {port} is now free")
else:
print_error(f"Port {port} is already in use!")
_print_port_help(port, processes_using_port)
return 1
# Handle frontend rebuild
if rebuild:
print(Colors.info("📦 Forcing frontend rebuild..."))
# Create a mock args object with debug flag
class BuildArgs:
debug = debug_mode
result = cmd_fe_build(BuildArgs())
if result != 0:
print_error("Frontend build failed. Server not started.")
return result
else:
# Auto-build frontend if needed (respects debug mode)
result = auto_build_frontend(debug=debug_mode)
if result is not None and result != 0:
print_error("Frontend build failed. Server not started.")
return result
auto_build_mkdocs()
update_js_cache()
mode_str = " (TEST MODE)" if test_mode else " (DEBUG MODE)" if debug_mode else ""
print(Colors.success(f"Starting LibreFolio API server{mode_str}..."))
print(Colors.warning(f"Database: {db}"))
print(Colors.warning(f"Host: {host}"))
print(Colors.warning(f"Port: {port}"))
if test_mode:
print()
print(f"{Colors.RED}{Colors.BOLD}⚠️ TEST MODE - Using test database! ⚠️{Colors.NC}")
# ("e2e_test_user", "e2e@test.example.com", "E2eTestPass123!"),
# ("e2e_test_admin", "e2eadmin@test.example.com", "E2eAdminPass123!"),
print(f"{Colors.RED}{Colors.BOLD}Note: defaults user in test db are:{Colors.NC}")
print(f'{Colors.RED}{Colors.BOLD} - {{"username": "e2e_test_user", "password": "E2eTestPass123!"}}')
print(f'{Colors.RED}{Colors.BOLD} - {{"username": "e2e_test_admin", "password": "E2eAdminPass123!"}}')
print()
if debug_mode:
print(Colors.warning("Log Level: DEBUG"))
if no_scheduler:
print(Colors.warning("⏸️ Scheduler: DISABLED (--no-scheduler)"))
print()
print(f"{Colors.BLUE}{Colors.BOLD}Available endpoints:{Colors.NC}")
print(f" ├── 🏠 {Colors.YELLOW}Frontend: http://localhost:{port}/{Colors.NC}")
print(f" ├── 💻 {Colors.YELLOW}API Redoc: http://localhost:{port}/api/v1/redoc{Colors.NC}")
print(f" ├── 🚀 {Colors.YELLOW}API Docs: http://localhost:{port}/api/v1/docs{Colors.NC}")
print(f" └── 📚 {Colors.YELLOW}User Doc: http://localhost:{port}/mkdocs/{Colors.NC}")
print()
if (PROJECT_ROOT / "frontend" / "build" / "index.html").exists():
print_success("Frontend build found - UI available at /")
else:
print_warning("No frontend build - run './dev.py front build' to enable UI")
if workers > 1:
print(f"{Colors.BLUE}Workers: {workers}{Colors.NC}")
print()
env = os.environ.copy()
if test_mode:
env["LIBREFOLIO_TEST_MODE"] = "1"
if debug_mode:
env["LIBREFOLIO_LOG_LEVEL"] = "DEBUG"
if no_scheduler:
env["LIBREFOLIO_NO_SCHEDULER"] = "1"
# Generate a shared JWT secret for all workers.
# On macOS, Python uses 'spawn' (not fork) for multiprocessing, so each
# uvicorn worker is a fresh process. Without a shared env var, each worker
# would generate its own random secret → tokens invalid across workers.
env.setdefault("JWT_SECRET", secrets.token_urlsafe(64))
if coverage_mode:
# Use 'coverage run --parallel-mode -m uvicorn' to track backend code
# coverage during E2E tests.
#
# NOTE: --reload is NOT used in coverage mode because 'coverage run'
# tracks only the direct process; reloader child processes bypass it.
#
# CRITICAL — SIGTERM propagation chain (3 levels of exec):
#
# When Playwright finishes E2E tests, it sends SIGTERM to the webServer
# process. For 'coverage run' to write .coverage.<pid> files, SIGTERM
# must reach it directly. The process chain uses exec at every level:
#
# 1. playwright.config.ts: 'exec ./dev.py ...' → /bin/sh replaces itself
# 2. dev.py (here): os.execvpe(pipenv, ...) → dev.py replaces itself
# 3. pipenv run: os.execvpe(coverage, ...) → pipenv replaces itself
#
# Result: single PID from Playwright → coverage run -m uvicorn.
# SIGTERM arrives directly, .coveragerc sigterm=true handles it,
# .coverage.<pid> file is written on graceful shutdown.
#
# Without exec at ANY level, subprocess.run() creates a child process,
# SIGTERM only reaches the parent, the child becomes an orphan, and
# no coverage data is ever written.
coveragerc = str(PROJECT_ROOT / ".coveragerc")
uvicorn_cmd = [
*pipenv_prefix(), "coverage", "run",
"--parallel-mode",
f"--rcfile={coveragerc}",
"-m", "uvicorn",
"backend.app.main:app",
"--host", host,
"--port", str(port),
]
print(f"{Colors.YELLOW}📊 Coverage tracking enabled via 'coverage run'{Colors.NC}")
print(f"{Colors.YELLOW} Config: {coveragerc}{Colors.NC}")
print(f"{Colors.YELLOW} Coverage data will be written to .coverage.<pid> on shutdown{Colors.NC}")
print()
# Replace this process with coverage run (execvpe never returns)
full_env = os.environ.copy()
full_env.update(env)
sys.stdout.flush()
sys.stderr.flush()
os.execvpe(uvicorn_cmd[0], uvicorn_cmd, full_env)
else:
uvicorn_cmd = [
*pipenv_prefix(), "python", "-c",
"import logging; logging.getLogger('watchfiles').setLevel(logging.WARNING); "
"import uvicorn.main; uvicorn.main.main()",
"backend.app.main:app",
"--host", host,
"--port", str(port),
]
if workers > 1:
uvicorn_cmd.extend(["--workers", str(workers)])
else:
uvicorn_cmd.append("--reload")
# Exclude the git directory and the configured data directory
uvicorn_cmd.extend([
"--reload-exclude", "**/.git/**",
])
try:
data_dir_path = get_data_dir(test_mode=test_mode).resolve()
try:
rel_data_dir = data_dir_path.relative_to(PROJECT_ROOT)
except ValueError:
rel_data_dir = data_dir_path
uvicorn_cmd.extend([
"--reload-exclude", f"**/{rel_data_dir}/**",
])
except Exception:
pass
# Always exclude the default backend/data folder recursively as well
uvicorn_cmd.extend([
"--reload-exclude", "**/backend/data/**",
])
return run_command_live(uvicorn_cmd, env=env)
# =============================================================================
# Backend Commands: Database
# =============================================================================
def cmd_db_check(args):
"""Verify CHECK constraints in database."""
db_path = args.path or get_database_path()
print(Colors.success(f"Checking database constraints: {db_path}"))
return run_pipenv(["python", "backend/test_scripts/verify_db_check_constraints.py", db_path])
def cmd_db_current(args):
"""Show current database migration."""
db_path = args.path or get_database_path()
print(Colors.success(f"Current migration for: {db_path}"))
env = {"DATABASE_URL": f"sqlite:///{PROJECT_ROOT / db_path}"} if db_path else {}
return run_command_live(
[*pipenv_prefix(), "alembic", "-c", "backend/alembic.ini", "current"],
env=env
)
def cmd_db_migrate(args):
"""Create a new migration."""
if not check_server_running("creating migrations", strict=True):
return 1
db_path = args.path or get_database_path()
message = args.message
print(Colors.success(f"Creating migration: {message}"))
env = {"DATABASE_URL": f"sqlite:///{PROJECT_ROOT / db_path}"} if db_path else {}
return run_command_live(
[*pipenv_prefix(), "alembic", "-c", "backend/alembic.ini", "revision", "--autogenerate", "-m", message],
env=env
)
def cmd_db_upgrade(args):
"""Apply pending migrations."""
if not check_server_running("applying migrations", strict=True):
return 1
db_path = args.path or get_database_path()
print(Colors.success(f"Upgrading database: {db_path}"))
env = {"DATABASE_URL": f"sqlite:///{PROJECT_ROOT / db_path}"} if db_path else {}
return run_command_live(
[*pipenv_prefix(), "alembic", "-c", "backend/alembic.ini", "upgrade", "head"],
env=env
)
def cmd_db_downgrade(args):
"""Rollback one migration."""
if not check_server_running("rolling back migrations", strict=True):
return 1
db_path = args.path or get_database_path()
print(Colors.success(f"Downgrading database: {db_path}"))
env = {"DATABASE_URL": f"sqlite:///{PROJECT_ROOT / db_path}"} if db_path else {}
return run_command_live(
[*pipenv_prefix(), "alembic", "-c", "backend/alembic.ini", "downgrade", "-1"],
env=env
)
def cmd_db_create_clean(args):
"""Delete database and recreate with latest migration."""
if not check_server_running("recreating database", strict=True):
return 1
test_mode = getattr(args, 'test', False)
if test_mode:
db_path = Path(get_test_database_path())
else:
db_path = Path(get_database_path())
full_path = PROJECT_ROOT / db_path
# Delete existing database if exists
if full_path.exists():
print(Colors.warning(f"Deleting existing database: {db_path}"))
full_path.unlink()
print_success("Database deleted")
else:
print(Colors.info(f"Database does not exist: {db_path}"))
# Create fresh database with migrations
print(Colors.success(f"Creating fresh database: {db_path}"))
env = os.environ.copy()
env["DATABASE_URL"] = f"sqlite:///{full_path}"
if test_mode:
env["LIBREFOLIO_TEST_MODE"] = "1"
result = run_command_live(
[*pipenv_prefix(), "alembic", "-c", "backend/alembic.ini", "upgrade", "head"],
env=env
)
if result == 0:
print_success(f"Database created successfully: {db_path}")
else:
print_error("Failed to create database")
return result
# =============================================================================
# Frontend Commands
# =============================================================================
def cmd_fe_dev(args):
"""Start frontend development server."""
print(Colors.success("Starting frontend development server..."))
print(Colors.warning("URL: http://localhost:5173"))
print()
return run_command_live(["npm", "run", "dev"], cwd=PROJECT_ROOT / "frontend")
def cmd_fe_build(args):
"""Build frontend for production."""
# Ensure fonts/JS libs exist before SvelteKit prerender (validates app.html refs)
update_js_cache()
# Sync API types to ensure frontend types are aligned with backend
print(Colors.success("Syncing API types before build..."))
sync_result = cmd_api_sync(args)
if sync_result != 0:
print_error("API sync failed - aborting build")
return sync_result
# Generate favicon from logo before build
generate_favicon()
# DIAGNOSTICS FOR GITHUB ACTIONS
print(Colors.info("[DEBUG] Running svelte-check..."))
run_command_live(["npx", "svelte-check", "--tsconfig", "./tsconfig.json"], cwd=PROJECT_ROOT / "frontend")
print(Colors.info("[DEBUG] END OF DIAGNOSTICS"))
if args.debug:
print(Colors.success("Building frontend in DEBUG mode (no minify, with sourcemaps)..."))
result = run_command_live(["npm", "run", "build:debug"], cwd=PROJECT_ROOT / "frontend")
else:
print(Colors.success("Building frontend for production..."))
result = run_command_live(["npm", "run", "build"], cwd=PROJECT_ROOT / "frontend")
if result == 0:
print_success("Frontend build complete!")
print(Colors.warning("Output in: frontend/build/"))
else:
print_error("Frontend build failed")
return result
def cmd_fe_check(args):
"""Run svelte-check for type errors."""
print(Colors.success("Running svelte-check for type errors..."))
return run_command_live(["npm", "run", "check"], cwd=PROJECT_ROOT / "frontend")
def cmd_fe_format(args):
"""Format frontend code with Prettier."""
if getattr(args, "check", False):
print(Colors.success("Checking frontend formatting with Prettier..."))
return run_command_live(["npm", "run", "format:check"], cwd=PROJECT_ROOT / "frontend")
else:
print(Colors.success("Formatting frontend code with Prettier..."))
return run_command_live(["npm", "run", "format"], cwd=PROJECT_ROOT / "frontend")
def cmd_fe_preview(args):
"""Preview production build."""
print(Colors.success("Previewing production build..."))
print(Colors.warning("URL: http://localhost:4173"))
print()
return run_command_live(["npm", "run", "preview"], cwd=PROJECT_ROOT / "frontend")
# =============================================================================
# API Schema Commands
# =============================================================================
def cmd_api_schema(args):
"""Export OpenAPI schema."""
print(Colors.success("Exporting OpenAPI schema..."))
return run_pipenv(["python", "scripts/list_api_endpoints.py", "--openapi-file", "frontend/src/lib/api/openapi.json"])
def cmd_api_client(args):
"""Generate TypeScript client from OpenAPI schema."""
print(Colors.success("Generating TypeScript client..."))
return run_command_live(
["npm", "run", "generate-api"],
cwd=PROJECT_ROOT / "frontend"
)
def cmd_api_sync(args):
"""Export schema and generate client."""
result = cmd_api_schema(args)
if result != 0:
return result
return cmd_api_client(args)
# =============================================================================
# Info Commands
# =============================================================================
def cmd_info_api(args):
"""List all API endpoints."""
print(Colors.success("Listing all API endpoints..."))
return run_pipenv(["python", "scripts/list_api_endpoints.py"])
def cmd_info_version(args):
"""Show application version from git tags."""
from backend.app.utils.version import get_version_info
version_info = get_version_info()
print(f"{Colors.CYAN}LibreFolio {version_info['version']}{Colors.NC}")
if version_info['is_dirty']:
print(f" {Colors.YELLOW}(uncommitted changes){Colors.NC}")
if version_info['is_release']:
print(f" {Colors.GREEN}Release version{Colors.NC}")
else:
print(f" Development version")
return 0
# =============================================================================
# MkDocs Commands
# =============================================================================
def _check_admonition_empty_lines():
"""Warn if any admonition is missing the empty line after !!!/???.
Without the empty line, Prettier removes the 4-space body indentation,
breaking the MkDocs admonition rendering.
Skips content inside fenced code blocks (``` or ~~~).
"""
docs_dir = PROJECT_ROOT / "mkdocs_src" / "docs"
adm_re = re.compile(r'^(?:!!!|[?]{3})\s+\w+')
fence_re = re.compile(r'^(`{3,}|~{3,})')
bad_files = []
for md_file in sorted(docs_dir.rglob("*.md")):
lines = md_file.read_text().splitlines()
in_fence = False
for i, line in enumerate(lines):
# Track fenced code blocks
if fence_re.match(line.strip()):
in_fence = not in_fence
continue
if in_fence:
continue
if adm_re.match(line):
if i + 1 < len(lines) and lines[i + 1].strip() != '':
if lines[i + 1].startswith(' '):
rel = md_file.relative_to(docs_dir)
bad_files.append(f" {rel}:{i + 1}")
break # one warning per file is enough
if bad_files:
print(Colors.warning(
f"⚠️ {len(bad_files)} file(s) have admonitions without empty line after !!!/??? "
f"(Prettier will break them):"
))
for f in bad_files[:10]:
print(f)
if len(bad_files) > 10:
print(f" ... and {len(bad_files) - 10} more")
print(Colors.info(
" Fix: add an empty line between the !!! directive and the indented body."
))
print()
def _check_image_paths_in_built_site():
"""Check that all <img src> paths in built HTML resolve to existing files.
Scans the built site for relative image paths under static/icons/ and
verifies each one exists on disk. Prints a visible warning if broken.
"""
site_dir = PROJECT_ROOT / "mkdocs_src" / "site"
if not site_dir.exists():
return
img_re = re.compile(r'<img[^>]+src="([^"]+)"')
broken = []
for html_file in sorted(site_dir.rglob("*.html")):
html_dir = html_file.parent
content = html_file.read_text(errors="ignore")
for match in img_re.finditer(content):
src = match.group(1)
# Only check relative paths to static/icons
if src.startswith(("http://", "https://", "data:", "/")) or "static/icons" not in src:
continue
resolved = (html_dir / src).resolve()
if not resolved.exists():
rel_html = html_file.relative_to(site_dir)
broken.append((str(rel_html), src))
if broken:
print()
print(Colors.warning(
f"⚠️ {len(broken)} broken icon path(s) found in built site:"
))
for html_path, img_src in broken[:20]:
print(f" ❌ {html_path}")
print(f" → {img_src}")
if len(broken) > 20:
print(f" ... and {len(broken) - 20} more")
print(Colors.info(
" Fix: use Markdown image syntax  instead of raw <img> for path auto-adjustment."
))
print()
else:
print(Colors.success("✅ All static icon paths in built site verified"))
def cmd_mkdocs_video(args):
"""Manage promotional video generation."""
action = args.action
video_dir = PROJECT_ROOT / "mkdocs_src" / "videoClipPrject" / "video_promo"
if not video_dir.exists():
print_error("Video project not found")
return 1
if action == "sync":
print(Colors.success("Syncing AI assets for video promo..."))
return run_command_live(["npm", "run", "sync"], cwd=video_dir)
elif action == "start":
print(Colors.success("Starting Remotion studio..."))
return run_command_live(["npm", "run", "start"], cwd=video_dir)
elif action == "build":
locale = getattr(args, "locale", "all")
print(Colors.success(f"Building promo videos ({locale})..."))
cmd = ["npm", "run", f"build:{locale}"]
return run_command_live(cmd, cwd=video_dir)
elif action == "review":
print(Colors.success("Generating review assets..."))
return run_command_live(["npm", "run", "review:assets", "--", "--clean"], cwd=video_dir)
else:
print_error(f"Unknown action: {action}")
return 1
def cmd_mkdocs_build(args):
"""Build MkDocs documentation."""
print(Colors.success("Building MkDocs site..."))
_check_admonition_empty_lines()
copy_docs_assets()
result = run_pipenv(["mkdocs", "build", "-f", "mkdocs_src/mkdocs.yml"])
if result == 0:
_check_image_paths_in_built_site()
return result
def cmd_mkdocs_serve(args):
"""Serve MkDocs documentation locally."""
print(Colors.success("Serving MkDocs site (http://127.0.0.1:6042)"))
copy_docs_assets()
return run_pipenv(["mkdocs", "serve", "-f", "mkdocs_src/mkdocs.yml", "-a", "127.0.0.1:6042"])
def cmd_mkdocs_clean(args):
"""Remove built site directory."""
print(Colors.warning("Removing site directory..."))
site_dir = PROJECT_ROOT / "mkdocs_src" / "site"
if site_dir.exists():
shutil.rmtree(site_dir)
print_success("Site directory removed")
return 0
def cmd_mkdocs_deploy(args):
"""Deploy MkDocs to GitHub Pages."""
print(Colors.success("Deploying MkDocs site to GitHub Pages..."))
copy_docs_assets()
return run_pipenv(["mkdocs", "gh-deploy", "--force", "-f", "mkdocs_src/mkdocs.yml"])
def cmd_mkdocs_gallery(args):
"""Generate gallery screenshots for documentation using Playwright."""
list_tests = getattr(args, 'list_tests', False)
filter_text = getattr(args, 'filter', None)
desktop_only = getattr(args, 'desktop_only', False)
mobile_only = getattr(args, 'mobile_only', False)
no_populate = getattr(args, 'no_populate', False)
test_port = getattr(args, 'test_port', None)
force = getattr(args, 'force', False)
# --list: show available test names and exit
if list_tests:
gallery_spec = PROJECT_ROOT / "frontend" / "e2e" / "gallery.spec.ts"
if not gallery_spec.exists():
print_error("gallery.spec.ts not found")
return 1
content = gallery_spec.read_text()
current_describe = ""
print(f"\n{Colors.CYAN}📸 Available Gallery Tests:{Colors.NC}")
print(f" Use {Colors.YELLOW}./dev.py mkdocs gallery -f \"<text>\"{Colors.NC} to filter\n")
for line in content.splitlines():
dm = re.search(r"test\.describe\('(.+?)'", line)
if dm:
current_describe = dm.group(1)
print(f" {Colors.GREEN}▸ {current_describe}{Colors.NC}")
tm = re.search(r"test\('(.+?)'", line)
if tm:
test_name = tm.group(1)
print(f" • {test_name}")
print()
return 0
print(Colors.success("Generating gallery screenshots for documentation..."))
if filter_text:
print(f"{Colors.YELLOW}Filter: only tests matching '{filter_text}'{Colors.NC}")
viewports = []
if not mobile_only:
viewports.append(('desktop', '📸 Running Desktop Screenshots...'))
if not desktop_only:
viewports.append(('mobile', '📱 Running Mobile Screenshots...'))
print(f"{Colors.BLUE}Viewports: {', '.join(v[0] for v in viewports)}{Colors.NC}")
print(f"{Colors.BLUE}Screenshots will be saved to mkdocs_src/docs/gallery/{Colors.NC}\n")
if not no_populate:
# Populate test database with realistic data (creates fresh DB with --force)
print(f"\n{Colors.CYAN}🗄️ Populating test database with sample data...{Colors.NC}")
result = subprocess.run(
["python", "dev.py", "test", "-q", "db", "populate", "--force", "--clean", "--with-static", "--with-reports"],
cwd=PROJECT_ROOT
)
if result.returncode != 0:
print_error("Failed to populate test database")
return 1
print_success("Test database populated")
# Ensure ALL test users exist
print(f"\n{Colors.YELLOW}Ensuring E2E test users exist...{Colors.NC}")
from scripts.test_runner import _ensure_test_users
if not _ensure_test_users():
print_error("Failed to create test users")
return 1
print_success("Test users ready")
else:
print(f"{Colors.YELLOW}⏭️ Skipping DB population (--no-populate){Colors.NC}")
failures = []
# Determine worker count: --workers flag or CPU count
explicit_workers = getattr(args, 'workers', None)
cpu_count = os.cpu_count() or 2
worker_count = explicit_workers if explicit_workers else max(2, cpu_count)
# Server workers: 1 per 4 browser workers, minimum 1
server_workers = max(1, math.ceil(worker_count / 4))
print(f"{Colors.BLUE}Browser workers: {worker_count} | Server workers: {server_workers}{Colors.NC}")
# --- Port conflict check ---
# Determine which port the test server will use
effective_port = test_port or os.environ.get('TEST_PORT') or get_test_server_port()
processes_using_port = check_port_in_use(int(effective_port))
if processes_using_port:
if force:
# --force: kill blocking processes and continue
pids = [pid for pid, _ in processes_using_port]
print_warning(f"Port {effective_port} is in use — killing {len(pids)} blocking process(es)...")
for pid, proc_name in processes_using_port:
try:
os.kill(pid, signal.SIGKILL)
print(f" ✗ Killed PID {pid} ({proc_name})")
except ProcessLookupError:
pass # already dead
except PermissionError:
print_error(f" Cannot kill PID {pid} ({proc_name}) — permission denied")
return 1
# Wait briefly for port to be released
time.sleep(1)
still_in_use = check_port_in_use(int(effective_port))
if still_in_use:
print_error(f"Port {effective_port} still in use after killing processes!")
_print_port_help(int(effective_port), still_in_use)
return 1
print_success(f"Port {effective_port} is now free")
else:
print_error(f"Port {effective_port} is already in use!")
_print_port_help(int(effective_port), processes_using_port)
print(f"\n{Colors.YELLOW}💡 Use --force to kill zombie processes, or use a different port:{Colors.NC}")
print(f" ./dev.py mkdocs gallery --force")
print(f" ./dev.py mkdocs gallery --test-port 8099\n")
return 1
# --- Headless by default (screenshots are pixel-perfect in headless mode) ---
use_headed = getattr(args, 'headed', False)
use_ui = getattr(args, 'ui', False)
if use_ui:
print(f"{Colors.YELLOW}🖥️ Running in Playwright UI mode (--ui){Colors.NC}")
elif use_headed:
print(f"{Colors.YELLOW}🖥️ Running in headed mode (--headed){Colors.NC}")
else:
print(f"{Colors.BLUE}🔇 Running in headless mode (use --headed for visible browser, --ui for interactive){Colors.NC}")
# Build a single Playwright command with all requested projects.
# This shares one webServer process across desktop+mobile, avoiding port conflicts.
cmd = [
"npm", "run", "test:e2e", "--",
"gallery.spec.ts",
"--workers", str(worker_count),
]
if use_ui:
cmd.append("--ui")
elif use_headed:
cmd.append("--headed")
for viewport, _label in viewports:
cmd.extend(["--project", viewport])
if filter_text:
cmd.extend(["-g", filter_text])
viewport_labels = ', '.join(v[0] for v in viewports)
print(f"\n{Colors.CYAN}📸 Running screenshots for: {viewport_labels}...{Colors.NC}")
# Pass server worker count + optional port via env so playwright.config.ts can use it
# Stream output live to terminal (no capture_output) so user sees progress
gallery_env = os.environ.copy()
gallery_env["GALLERY_SERVER_WORKERS"] = str(server_workers)
# Always disable the scheduler during gallery runs — prevents live data updates
# from changing charts/numbers between screenshots.
gallery_env["LIBREFOLIO_NO_SCHEDULER"] = "1"
if test_port:
gallery_env["TEST_PORT"] = str(test_port)
run_cmd = cmd
try:
# Use Popen to stream output live AND capture it for failure parsing
proc = subprocess.Popen(
run_cmd, cwd=PROJECT_ROOT / "frontend", env=gallery_env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
output_lines = []
for line in proc.stdout:
print(line, end='')
output_lines.append(line)
proc.wait()
returncode = proc.returncode
except KeyboardInterrupt:
print(f"\n{Colors.YELLOW}⚠️ Gallery interrupted by user (Ctrl+C){Colors.NC}")
print(f"{Colors.YELLOW}Partial screenshots may have been saved to mkdocs_src/docs/gallery/{Colors.NC}")
return 1
# Parse failed test names from Playwright output
# Playwright prints lines like:
# [desktop] › e2e/gallery.spec.ts:330:9 › Gallery Screenshots › Files › test name ───────
failed_tests = [] # list of (viewport, test_name) tuples
if returncode != 0:
failures = [v[0] for v in viewports]
in_failures_block = False
for line in output_lines:
stripped = line.strip()
# Detect the failures summary block (e.g. " 1 failed")
if re.match(r'^\d+ failed$', stripped):
in_failures_block = True
continue
if in_failures_block:
# Lines like: [desktop] › e2e/gallery.spec.ts:330:9 › Gallery Screenshots › Files › test name ───
m = re.match(r'\[([\w]+)\]\s+›\s+\S+\s+›\s+Gallery Screenshots\s+›\s+(.+)', stripped)
if m:
viewport = m.group(1).strip() # 'desktop' or 'mobile'
test_name = m.group(2).strip() # 'FX › Chart settings modal ───────'
failed_tests.append((viewport, test_name))
elif stripped and not stripped.startswith('['):
# End of failures block (e.g. "X passed", empty line, etc.)
in_failures_block = False
print_error(f"Gallery generation had failures (see above)")
if failures:
print(f"\n{Colors.YELLOW}⚠️ Gallery generation completed with failures in: {', '.join(failures)}{Colors.NC}")
if failed_tests:
print(f"\n{Colors.YELLOW}Failed tests:{Colors.NC}")
for _vp, t in failed_tests:
print(f" ✗ {t}")
print(f"\n{Colors.CYAN}💡 Retry failed tests with:{Colors.NC}")
# Group by test name to detect which viewports failed
from collections import defaultdict
by_test: dict[str, list[str]] = defaultdict(list)
for vp, t in failed_tests:
# Strip trailing ─── decoration for the filter text
clean_name = re.sub(r'\s*─+\s*$', '', t).strip()
by_test[clean_name].append(vp)
for test_name, vps in by_test.items():
has_desktop = 'desktop' in vps
has_mobile = 'mobile' in vps
if has_desktop:
print(f" ./dev.py mkdocs gallery --no-populate --desktop-only -f \"{test_name}\"")
if has_mobile:
print(f" ./dev.py mkdocs gallery --no-populate --mobile-only -f \"{test_name}\"")
if has_desktop and has_mobile:
print(f" ./dev.py mkdocs gallery --no-populate -f \"{test_name}\" # both viewports")
print()
else:
print(f"{Colors.YELLOW}Some screenshots may be missing or outdated. Run with --filter to retry specific tests.{Colors.NC}")
else:
print_success("\n✅ Gallery screenshots generated successfully!")
print(f"{Colors.GREEN}Output: mkdocs_src/docs/gallery/{Colors.NC}")
return 1 if failures else 0
def cmd_mkdocs_check_links(args):
"""Validate cross-boundary links: frontend/backend → MkDocs docs.
Scope 1: Frontend docsPath / /mkdocs/ URLs → docs file existence + anchor check.
Scope 2: Backend provider docs_url → docs file existence.
"""
docs_root = PROJECT_ROOT / "mkdocs_src" / "docs"
frontend_src = PROJECT_ROOT / "frontend" / "src"
errors = []
ok_count = 0
print(Colors.success("🔗 Checking cross-boundary links (frontend/backend → docs)...\n"))
# ── Scope 1: Frontend → docs ──────────────────────────────────────────
print(f"{Colors.CYAN}── Scope 1: Frontend → MkDocs ──{Colors.NC}")
# 1a. Collect docsPath values from .ts and .svelte files
docs_paths: list[tuple[str, str, int]] = [] # (path, file, line)
for ext in ("*.ts", "*.svelte"):
for f in frontend_src.rglob(ext):
for i, line in enumerate(f.read_text().splitlines(), 1):
# static docsPath = '...' or docsPath: '...'
m = re.search(r"""docsPath\s*[:=]\s*['"]([^'"]+)['"]""", line)
if m:
docs_paths.append((m.group(1), str(f.relative_to(PROJECT_ROOT)), i))
# 1b. Collect /mkdocs/ URLs from window.open and href=
for ext in ("*.ts", "*.svelte"):
for f in frontend_src.rglob(ext):
for i, line in enumerate(f.read_text().splitlines(), 1):
m = re.search(r"""/mkdocs/([^'"`,\s)]+)""", line)
if m:
raw = m.group(1).rstrip("/")
# Skip template variables like ${prefix}
if "${" in raw:
# Extract after the template var — e.g. ${prefix}user/assets → user/assets
clean = re.sub(r"\$\{[^}]+\}", "", raw).lstrip("/")
if clean:
docs_paths.append((clean, str(f.relative_to(PROJECT_ROOT)), i))
elif ":path" not in raw:
docs_paths.append((raw, str(f.relative_to(PROJECT_ROOT)), i))
# Deduplicate
seen = set()
unique_paths = []
for path, src_file, line_no in docs_paths: