From 626c35057cd8fc7fc72f4b0c623f7e451eb51d4f Mon Sep 17 00:00:00 2001 From: tisachi Date: Tue, 27 Oct 2026 21:34:51 +0100 Subject: [PATCH] =?UTF-8?q?Ops:=20narz=C4=99dzie=20fitos=20=E2=80=94=20CLI?= =?UTF-8?q?=20+=20menu=20PowerShell=20do=20powtarzalnych=20operacji=20(sta?= =?UTF-8?q?tus,=20check,=20guard=20i18n,=20lint/format,=20testy,=20docker?= =?UTF-8?q?=20up/rebuild/ps/logs/restart/down,=20backup=20bazy,=20prisma,?= =?UTF-8?q?=20deploy=20z=20refa,=20git)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/tools/README.md | 52 ++++ ops/tools/fitos.cmd | 4 + ops/tools/fitos.ps1 | 4 + ops/tools/fitos.py | 740 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 800 insertions(+) create mode 100644 ops/tools/README.md create mode 100644 ops/tools/fitos.cmd create mode 100644 ops/tools/fitos.ps1 create mode 100644 ops/tools/fitos.py diff --git a/ops/tools/README.md b/ops/tools/README.md new file mode 100644 index 0000000..86b727f --- /dev/null +++ b/ops/tools/README.md @@ -0,0 +1,52 @@ +# FitOS — narzędzia terminalowe + +Jedno menu do powtarzalnych operacji: status, testy, lint, stack Docker, +baza/Prisma, dev serwery, git i deploy. Bez klepania komend z klawiatury. + +## Uruchomienie + +```powershell +.\ops\tools\fitos.ps1 # interaktywne menu +.\ops\tools\fitos.ps1 status # tryb CLI (bez menu — szybki, dla agentów) +``` + +Wymaga `python` w PATH (to samo co `ops/deploy/deploy.ps1`). + +## Co jest w menu + +| Pozycja | Co robi | +|---|---| +| status | branch + brudne/niepushnięte + kontenery fitos + health 900x | +| check | pełna bramka: strażnik i18n + lint + format --check + testy unit (wszystkie pakiety) | +| lint/format | `npm run lint [-- --fix]` / `npm run format` per pakiet, lokalne `.prettierrc.json` | +| strażnik i18n | grep liter PL w `app|admin|web/src` poza `src/i18n/locales/**` | +| testy | unit (api/app/admin/web), e2e Playwright (app/admin), playwright install | +| stack | `docker compose up -d --build`, rebuild, `down` (zawsze bez `-v`), ps, logs, restart | +| dev | `npm run dev` dla api/app/admin/web | +| db | backup `pg_dump` -> `ops/tools/backups/`, prisma format/migrate/generate/seed/studio | +| deploy | tylko przez `ops/deploy/deploy.py`, ZAWSZE z refa (`origin/main` albo wpisany tag); prod = potwierdzenie `prod`; `--reset-db` tylko staging z potwierdzeniem | +| git | status / log / unpushed / fetch / pull --ff-only | +| env | wersje narzędzi, daemon Dockera, `api/.env`, `node_modules`, `.deploy.staging.env` | + +## Zasady bezpieczeństwa wbudowane w narzędzie + +- **Nigdy nie kasuje wolumenów** — lokalne `down` nigdy nie dostaje `-v`; + `fitos_pgdata` jest nietykalny. Reset bazy istnieje tylko jako `--reset-db` + deploy.py dla **stagingu**, z podwójnym potwierdzeniem. +- Deploy prod wymaga wpisania `prod`; deploy zawsze z refa gita (nigdy z drzewa roboczego). +- Backup bazy jest wyłącznie odczytowy (`pg_dump` przez `exec`). + +## Tryb CLI — skróty przydatne agentom (mało tokenów) + +```powershell +python ops/tools/fitos.py status # 1 ekran: git + docker + health +python ops/tools/fitos.py guard # strażnik i18n, wynik FAIL/OK +python ops/tools/fitos.py check # lint+format+unit+guard w jednym przebiegu +python ops/tools/fitos.py test unit api +python ops/tools/fitos.py test e2e app +python ops/tools/fitos.py rebuild app +python ops/tools/fitos.py backup +python ops/tools/fitos.py deploy staging --ref v1.2.3 +``` + +Artefakty: backupy lądują w `ops/tools/backups/` (gitignore). diff --git a/ops/tools/fitos.cmd b/ops/tools/fitos.cmd new file mode 100644 index 0000000..59f9ab1 --- /dev/null +++ b/ops/tools/fitos.cmd @@ -0,0 +1,4 @@ +@echo off +rem FitOS tools launcher (cmd). Uruchom: ops\tools\fitos.cmd [podkomenda] +python "%~dp0fitos.py" %* +exit /b %ERRORLEVEL% diff --git a/ops/tools/fitos.ps1 b/ops/tools/fitos.ps1 new file mode 100644 index 0000000..baf7670 --- /dev/null +++ b/ops/tools/fitos.ps1 @@ -0,0 +1,4 @@ +# FitOS tools — launcher (Windows). Uruchom: .\ops\tools\fitos.ps1 [podkomenda] +# Wymaga python w PATH (jak ops/deploy/deploy.ps1). +& python "$PSScriptRoot/fitos.py" @args +exit $LASTEXITCODE diff --git a/ops/tools/fitos.py b/ops/tools/fitos.py new file mode 100644 index 0000000..1565606 --- /dev/null +++ b/ops/tools/fitos.py @@ -0,0 +1,740 @@ +#!/usr/bin/env python3 +"""FitOS — menu terminalowe do powtarzalnych operacji (dev + deploy + testy). + +Uruchom: ops/tools/fitos.ps1 (interaktywne menu) +Tryb CLI: ops/tools/fitos.ps1 lint app (bez menu — dla agentow i skryptow) + +Zasady: +- 100% stdlib; wywoluje istniejace narzedzia repo (npm, docker compose, git, deploy.py). +- Nikdy nie dotyka wolumenu fitos_pgdata (down BEZ -v; backup tylko odczytowy). +- Deploy tylko przez ops/deploy/deploy.py (z refa gita); prod = podwojne potwierdzenie. +""" + +from __future__ import annotations + +import argparse +import re +import shutil +import subprocess +import sys +import urllib.request +from datetime import datetime +from pathlib import Path + +TOOLS_DIR = Path(__file__).resolve().parent +REPO_ROOT = TOOLS_DIR.parent.parent +for _stream in (sys.stdout, sys.stderr): + if hasattr(_stream, "reconfigure"): + _stream.reconfigure(encoding="utf-8", errors="replace") +PACKAGES = ("api", "app", "admin", "web") +PL_CHARS = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]") +LOCAL_HEALTH = ( + ("api", "http://localhost:9002/health"), + ("app", "http://localhost:9001/health"), + ("admin", "http://localhost:9000/health"), + ("web", "http://localhost:9003/health"), +) + + +def c(text: str, code: str) -> str: + return f"\033[{code}m{text}\033[0m" if sys.stdout.isatty() else text + + +def head(msg: str) -> None: + print("\n" + c(f"=== {msg} ===", "1;36")) + + +def info(msg: str) -> None: + print(c(f" {msg}", "90")) + + +def ok(msg: str) -> None: + print(c(f" OK {msg}", "92")) + + +def warn(msg: str) -> None: + print(c(f" !! {msg}", "93")) + + +def fail(msg: str) -> None: + print(c(f" FAIL {msg}", "91")) + + +def run(args: list[str], cwd: Path | None = None, quiet: bool = False) -> int: + """Uruchamia polecenie (bez shell — bez problemow z cytatem na Windows). + + .cmd/.bat/.ps1 shimy (npm, npx) wymagaja otoczki — CreateProcess ich nie + startuje bezposrednio. + """ + args = resolve_cmd(args) + if not quiet: + info("$ " + " ".join(args)) + proc = subprocess.run(args, cwd=str(cwd or REPO_ROOT)) + return proc.returncode + + +def resolve_cmd(args: list[str]) -> list[str]: + exe = shutil.which(args[0]) if args and " " not in args[0] and not Path(args[0]).is_absolute() else None + if not exe: + return args + low = exe.lower() + if low.endswith((".cmd", ".bat")): + return ["cmd", "/c", exe, *args[1:]] + if low.endswith(".ps1"): + return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", exe, *args[1:]] + return [exe, *args[1:]] + + +def run_all(steps: list[tuple[str, list[str], Path]], stop_on_fail: bool = True) -> bool: + fails = [] + for label, args, cwd in steps: + head(label) + if run(args, cwd=cwd) != 0: + fails.append(label) + if stop_on_fail: + break + for label in fails: + fail(label) + if not fails: + ok("wszystko przeszlo") + return not fails + + +def confirm(prompt: str, expected: str) -> bool: + try: + return input(c(f"{prompt} (wpisz '{expected}'): ", "1;33")).strip() == expected + except (EOFError, KeyboardInterrupt): + return False + + +def ask_choice(prompt: str, choices: list[str], default: str = "") -> str: + print(" " + prompt) + for i, item in enumerate(choices, 1): + print(f" {i}) {item}") + raw = input(c(" wybor: ", "1;36")).strip() + if not raw and default: + return default + if raw.isdigit() and 1 <= int(raw) <= len(choices): + return choices[int(raw) - 1] + return raw + + +def ask_packages(default: str = "all") -> list[str]: + raw = input(c(" pakiety (api/app/admin/web/all): ", "1;36")).strip().lower() or default + if raw in ("all", ""): + return list(PACKAGES) + parts = [p.strip() for p in re.split(r"[,\s]+", raw) if p.strip()] + bad = [p for p in parts if p not in PACKAGES] + if bad: + warn("nieznane pakiety: " + ", ".join(bad)) + return [p for p in parts if p in PACKAGES] + + +def compose(pkg: str) -> list[str]: + return ["docker", "compose", "-f", str(REPO_ROOT / pkg / "docker-compose.yml")] + + +# --- status / summary ---------------------------------------------------------- + +def http_ok(url: str) -> bool: + try: + with urllib.request.urlopen(url, timeout=2) as resp: + return resp.status == 200 + except Exception: + return False + + +def cmd_summary() -> int: + head("Podsumowanie") + branch = subprocess.run(["git", "branch", "--show-current"], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip() + dirty = subprocess.run(["git", "status", "--porcelain"], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip() + unpushed = subprocess.run(["git", "log", "@{u}..HEAD", "--oneline"], cwd=REPO_ROOT, capture_output=True, text=True).stdout.strip() + print(f" branch: {branch or '(odłączony HEAD)'} | brudne pliki: {len(dirty.splitlines()) if dirty else 0}" + f" | niepushnięte: {len(unpushed.splitlines()) if unpushed else 0}") + if unpushed: + info("niepushnięte: " + " / ".join(unpushed.splitlines())) + proc = subprocess.run( + ["docker", "ps", "--filter", "name=fitos", "--format", "{{.Names}} {{.Status}}"], + capture_output=True, text=True, + ) + if proc.returncode != 0: + fail("docker nie odpowiada") + return 1 + lines = [ln for ln in proc.stdout.splitlines() if ln.strip()] + print(" kontenery: " + (", ".join(lines) if lines else "(żadne nie działają)")) + for name, url in LOCAL_HEALTH: + mark = c("UP", "92") if http_ok(url) else c("—", "90") + print(f" {name:<6} {url:<34} {mark}") + return 0 + + +# --- lint / format / guard ------------------------------------------------------ + +def cmd_lint(packages: list[str], fix: bool = False) -> int: + args_lint = (["npm", "run", "lint", "--", "--fix"] if fix else ["npm", "run", "lint"]) + return 0 if run_all([(f"lint {p}", args_lint, REPO_ROOT / p) for p in packages]) else 1 + + +def cmd_format(packages: list[str], check_only: bool = False) -> int: + steps = [] + for p in packages: + args = ["npm", "run", "format"] + if check_only: + args += ("--", "--check") if p != "api" else ["npx", "prettier", "--check", "src", "prisma"] + steps.append((f"format {p}", args, REPO_ROOT / p)) + return 0 if run_all(steps) else 1 + + +def scan_pl_literals(src: str) -> list[tuple[int, str]]: + """Zwraca (linia, tekst) dla liter PL w literalach stringowych kodu. + + Skan znak po znaku: komentuje // i /* */ (w tym JSX) oraz pomija treść + stringów ' " ` jako literals — tylko tam mogą (nie mogą) być znaki PL. + """ + hits: list[tuple[int, str]] = [] + i, line, n = 0, 1, len(src) + state = "code" + while i < n: + ch = src[i] + nxt = src[i + 1] if i + 1 < n else "" + if ch == "\n": + line += 1 + if state == "line_comment": + state = "code" + i += 1 + continue + if state == "code": + if ch == "/" and nxt == "/": + state = "line_comment" + i += 2 + elif ch == "/" and nxt == "*": + state = "block_comment" + i += 2 + elif ch in "\"'`": + state = ch + start, i = i, i + 1 + buf = [] + while i < n: + cc = src[i] + if cc == "\\": + i += 2 + continue + if cc == "\n": + if state != "`": + break + line += 1 + buf.append("\n") + i += 1 + continue + if cc == state: + i += 1 + break + buf.append(cc) + i += 1 + text = "".join(buf) + if PL_CHARS.search(text): + hits.append((line, text[:90])) + else: + i += 1 + elif state == "line_comment": + i += 1 + else: # block_comment + if ch == "*" and nxt == "/": + state = "code" + i += 2 + else: + i += 1 + return hits + + +def cmd_guard() -> int: + """Strażnik i18n: litery PL w literalach stringowych (app/admin/web src, + poza src/i18n/locales). Komentarze po polsku są dozwolone.""" + head("Strażnik i18n (litery PL w stringach poza locales)") + hits = 0 + for pkg in ("app", "admin", "web"): + src_dir = REPO_ROOT / pkg / "src" + if not src_dir.is_dir(): + continue + for f in sorted(src_dir.rglob("*")): + if not f.is_file() or f.suffix not in (".ts", ".tsx", ".js", ".jsx"): + continue + if "i18n" in f.parts and "locales" in f.parts: + continue + try: + content = f.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + for n, text in scan_pl_literals(content): + print(f" {f.relative_to(REPO_ROOT)}:{n}: \"{text}\"") + hits += 1 + if hits: + fail(f"{hits} literal(i) PL poza locales") + return 1 + ok("czysto — brak liter PL poza locales") + return 0 + + +def cmd_check() -> int: + """Pełna bramka: guard + lint + format --check + unit testy.""" + ok_flag = True + ok_flag &= cmd_guard() == 0 + ok_flag &= cmd_lint(list(PACKAGES)) + ok_flag &= cmd_format(list(PACKAGES), check_only=True) + ok_flag &= cmd_tests("unit", list(PACKAGES)) == 0 + return 0 if ok_flag else 1 + + +# --- testy ----------------------------------------------------------------------- + +def cmd_tests(kind: str, packages: list[str], watch: bool = False) -> int: + script = { + "unit": "test:watch" if watch else "test", + "e2e": "test:e2e", + "e2e:ui": "test:e2e:ui", + "e2e:install": "test:e2e:install", + }[kind] + steps = [] + for p in packages: + pkg_json = (REPO_ROOT / p / "package.json").read_text(encoding="utf-8") + if f'"{script}"' not in pkg_json: + info(f"pomiń {p} (brak skryptu {script})") + continue + steps.append((f"{kind} {p}", ["npm", "run", script], REPO_ROOT / p)) + return 0 if run_all(steps) else 1 + + +# --- docker (stack lokalny) ------------------------------------------------------- + +def ensure_net() -> None: + proc = subprocess.run(["docker", "network", "inspect", "fitos-net"], capture_output=True) + if proc.returncode != 0: + head("Tworzę sieć fitos-net (raz, wymagana przez fronty)") + run(["docker", "network", "create", "fitos-net"]) + + +def cmd_stack_up(packages: list[str]) -> int: + ensure_net() + steps = [] + for p in (pkg for pkg in ("api", "app", "admin", "web") if pkg in packages): + steps.append((f"build+up {p}", [*compose(p), "up", "-d", "--build"], REPO_ROOT)) + return 0 if run_all(steps) else 1 + + +def cmd_stack_rebuild(packages: list[str]) -> int: + steps = [] + for p in packages: + steps.append((f"rebuild {p}", [*compose(p), "build"], REPO_ROOT)) + steps.append((f"up {p}", [*compose(p), "up", "-d"], REPO_ROOT)) + return 0 if run_all(steps) else 1 + + +def cmd_stack_down() -> int: + # ZAWSZE bez -v: wolumeny danych (fitos_pgdata!) musza przetrwac. + head("docker compose down (api+db) — wolumeny NIE sa kasowane") + if not confirm("Zatrzymać lokalny stos api+db?", "down"): + warn("przerwano") + return 1 + return run([*compose("api"), "down", "--remove-orphans"]) + + +def cmd_ps() -> int: + return run(["docker", "ps", "-a", "--filter", "name=fitos", "--format", "table {{.Names}}\t{{.Status}}\t{{.Ports}}"]) + + +def cmd_logs(service: str, tail: int = 100, follow: bool = False) -> int: + pkg = "api" if service in ("api", "db") else service + args = [*compose(pkg), "logs", "--tail", str(tail)] + if follow: + args.append("-f") + return run(args) + + +def cmd_restart(service: str) -> int: + pkg = "api" if service in ("api", "db") else service + return run([*compose(pkg), "restart"]) + + +# --- baza / prisma ----------------------------------------------------------------- + +def cmd_backup() -> int: + out_dir = TOOLS_DIR / "backups" + out_dir.mkdir(exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d-%H%M%S") + out_file = out_dir / f"fitos-db-{stamp}.sql" + head("Backup bazy (pg_dump z kontenera fitos-db — tylko odczyt)") + proc = subprocess.run( + resolve_cmd([*compose("api"), "exec", "-T", "db", "pg_dump", "-U", "fitos", "fitos"]), + stdout=open(out_file, "wb"), + ) + if proc.returncode != 0 or out_file.stat().st_size == 0: + out_file.unlink(missing_ok=True) + fail("pg_dump nieudany (czy fitos-db działa?)") + return 1 + mb = out_file.stat().st_size / (1024 * 1024) + ok(f"zapisano {out_file.relative_to(REPO_ROOT)} ({mb:.1f} MB)") + return 0 + + +def cmd_prisma(action: str) -> int: + args = { + "format": ["npx", "prisma", "format"], + "migrate": ["npm", "run", "prisma:migrate"], + "generate": ["npm", "run", "prisma:generate"], + "seed": ["npm", "run", "seed"], + "studio": ["npx", "prisma", "studio"], + }[action] + return run(args, cwd=REPO_ROOT / "api") + + +def menu_db() -> int: + last = 0 + while True: + print("\n" + c("--- Baza / Prisma ---", "1;36")) + print(" 1) backup bazy (pg_dump -> ops/tools/backups)") + print(" 2) prisma format (po zmianie schema.prisma)") + print(" 3) prisma migrate dev (tworzy+aplikuje migrację)") + print(" 4) prisma generate") + print(" 5) seed") + print(" 6) prisma studio") + print(" 0) wróć") + choice = input(c(" wybor: ", "1;36")).strip() + if choice in ("", "0"): + return last + mapping = {"1": cmd_backup, "2": lambda: cmd_prisma("format"), "3": lambda: cmd_prisma("migrate"), + "4": lambda: cmd_prisma("generate"), "5": lambda: cmd_prisma("seed"), "6": lambda: cmd_prisma("studio")} + if choice in mapping: + last = mapping[choice]() + if choice == "3": + warn("po zmianie schema: upewnij się, że `npx prisma format` (poz. 2) wykonał się PRZED migrate") + + +# --- deploy ------------------------------------------------------------------------- + +def cmd_deploy(env: str, ref: str, extra: list[str]) -> int: + head(f"Deploy -> {env} (ref: {ref})") + info("deploy.py: git archive refa -> scp -> compose build/up -> /health -> smoke") + if env == "prod": + warn("PROD — wymagane świadome potwierdzenie") + if not confirm("Potwierdź deploy na PRODUKCJĘ", "prod"): + warn("przerwano") + return 1 + args = [sys.executable, str(REPO_ROOT / "ops" / "deploy" / "deploy.py"), "-e", env, "--ref", ref, *extra] + return run(args) + + +def menu_deploy() -> int: + last = 0 + while True: + print("\n" + c("--- Deploy (tylko z refa gita, przez ops/deploy/deploy.py) ---", "1;36")) + print(" 1) staging — origin/main") + print(" 2) staging — własny ref (branch/tag/SHA)") + print(" 3) prod — origin/main (podwojne potwierdzenie)") + print(" 4) prod — własny ref") + print(" 5) staging --reset-db (kasacja wolumenów STAGINGU + seed)") + print(" 0) wróć") + choice = input(c(" wybor: ", "1;36")).strip() + if choice in ("", "0"): + return last + if choice in ("1", "2", "3", "4"): + env = "staging" if choice in ("1", "2") else "prod" + ref = "origin/main" if choice in ("1", "3") else input(" ref: ").strip() + if not ref: + warn("pusty ref — przerwano (deploy zawsze z refa)") + continue + last = cmd_deploy(env, ref, []) + elif choice == "5": + warn("reset kasuje DANE STAGINGU (wolumeny PGDATA/UPLOADS z .deploy.staging.env).") + warn("Lokalnego fitos_pgdata to nie dotyczy — tutaj nie zagląda.") + if confirm("Wpisać 'reset' aby przejść do deploy.py z --reset-db", "reset"): + last = cmd_deploy("staging", "origin/main", ["--reset-db"]) + else: + warn("przerwano") + + +# --- dev serwery ---------------------------------------------------------------------- + +def cmd_dev(pkg: str) -> int: + head(f"Dev serwer: {pkg} (Ctrl+C aby zatrzymać; inny pakiet = osobne okno)") + if pkg == "api": + info("wymaga działającego PostgreSQL (docker: stos api) albo lokalnej bazy") + if pkg in ("app", "admin"): + info("vite proxy /api -> localhost:9002 (API musi stać)") + return run(["npm", "run", "dev"], cwd=REPO_ROOT / pkg) + + +# --- git --------------------------------------------------------------------------------- + +def cmd_git(action: str) -> int: + args = { + "status": ["git", "status", "-sb"], + "log": ["git", "log", "--oneline", "-15"], + "unpushed": ["git", "log", "@{u}..HEAD", "--oneline"], + "fetch": ["git", "fetch", "--prune"], + "pull": ["git", "pull", "--ff-only"], + }[action] + return run(args) + + +# --- środowisko ---------------------------------------------------------------------------- + +def cmd_envcheck() -> int: + head("Kontrola środowiska") + problems = 0 + for name, args in ( + ("python", [sys.executable, "--version"]), + ("node", ["node", "--version"]), + ("npm", ["npm", "--version"]), + ("git", ["git", "--version"]), + ("docker", ["docker", "--version"]), + ): + try: + proc = subprocess.run(resolve_cmd(args), capture_output=True, text=True) + line = (proc.stdout or proc.stderr).strip().splitlines()[0] if (proc.stdout or proc.stderr) else "?" + ok(f"{name}: {line}") + except FileNotFoundError: + fail(f"{name}: brak w PATH") + problems += 1 + if subprocess.run(["docker", "info", "--format", "{{.ServerVersion}}"], capture_output=True, text=True).returncode != 0: + fail("daemon Dockera nie odpowiada") + problems += 1 + else: + ok("docker daemon: działa") + if not (REPO_ROOT / "api" / ".env").is_file(): + warn("brak api/.env (wymagany do lokalnego stosu: copy .env.example .env)") + for p in PACKAGES: + if not (REPO_ROOT / p / "node_modules").is_dir(): + warn(f"{p}/node_modules brak — uruchom `npm install` w {p}/") + if not (REPO_ROOT / "ops" / "deploy" / ".deploy.staging.env").is_file(): + warn("brak ops/deploy/.deploy.staging.env — deploy nie ruszy (skopiuj z .example)") + else: + ok("ops/deploy/.deploy.staging.env: jest") + return 1 if problems else 0 + + +# --- menu ------------------------------------------------------------------------- + +MAIN_MENU = [ + ("status", "Podsumowanie (git + kontenery + health)"), + ("check", "Pełna bramka: guard + lint + format + testy unit"), + ("lint", "Lint / format"), + ("testy", "Testy (unit / e2e / playwright install)"), + ("stack", "Stack lokalny (up / rebuild / down / ps / logs)"), + ("dev", "Dev serwery (npm run dev)"), + ("db", "Baza / Prisma (backup, migracje, seed, studio)"), + ("deploy", "Deploy staging / prod (z refa, przez deploy.py)"), + ("git", "Git (status / log / unpushed / fetch / pull)"), + ("env", "Kontrola środowiska"), +] + + +def sub_choice(title: str, options: list[str]) -> str: + print("\n" + c(f"--- {title} ---", "1;36")) + for i, opt in enumerate(options, 1): + print(f" {i}) {opt}") + print(" 0) wróć") + return input(c(" wybor: ", "1;36")).strip() + + +def menu_lint() -> int: + last = 0 + while True: + choice = sub_choice("Lint / format", [ + "lint — wszystkie pakiety", + "lint --fix — wszystkie pakiety", + "lint — wybrane pakiety", + "format --check — wszystkie", + "format (zapis) — wszystkie", + "strażnik i18n (litery PL w src)", + ]) + if choice in ("", "0"): + return last + pkgs = list(PACKAGES) + if choice == "3": + pkgs = ask_packages() or pkgs + last = { + "1": lambda: cmd_lint(pkgs), + "2": lambda: cmd_lint(pkgs, fix=True), + "3": lambda: cmd_lint(pkgs), + "4": lambda: cmd_format(pkgs, check_only=True), + "5": lambda: cmd_format(pkgs), + "6": cmd_guard, + }[choice]() + + +def menu_tests() -> int: + last = 0 + while True: + choice = sub_choice("Testy", [ + "unit — wszystkie pakiety", + "unit — wybrane pakiety", + "unit watch (api)", + "e2e (app)", + "e2e (admin)", + "e2e — app + admin", + "playwright install chromium (app)", + "playwright install chromium (admin)", + ]) + if choice in ("", "0"): + return last + if choice == "1": + last = cmd_tests("unit", list(PACKAGES)) + elif choice == "2": + last = cmd_tests("unit", ask_packages()) + elif choice == "3": + last = cmd_tests("unit", ["api"], watch=True) + elif choice == "4": + last = cmd_tests("e2e", ["app"]) + elif choice == "5": + last = cmd_tests("e2e", ["admin"]) + elif choice == "6": + last = cmd_tests("e2e", ["app", "admin"]) + elif choice in ("7", "8"): + last = cmd_tests("e2e:install", ["app" if choice == "7" else "admin"]) + return last + + +def menu_stack() -> int: + last = 0 + while True: + choice = sub_choice("Stack lokalny (docker)", [ + "up + build — całość (api, app, admin, web)", + "up + build — wybrane pakiety", + "rebuild — wybrane pakiety (build + up -d)", + "down api+db (wolumeny zostają!)", + "ps — kontenery fitos", + "logs — serwis", + "restart — serwis", + ]) + if choice in ("", "0"): + return last + if choice == "1": + last = cmd_stack_up(list(PACKAGES)) + elif choice == "2": + last = cmd_stack_up(ask_packages()) + elif choice == "3": + last = cmd_stack_rebuild(ask_packages()) + elif choice == "4": + last = cmd_stack_down() + elif choice == "5": + last = cmd_ps() + elif choice in ("6", "7"): + svc = ask_choice("serwis:", ["api", "db", "app", "admin", "web"]) + if svc in ("api", "db", "app", "admin", "web"): + if choice == "6": + follow = input(" śledzić na żywo? (t/n): ").strip().lower() == "t" + last = cmd_logs(svc, follow=follow) + else: + last = cmd_restart(svc) + + +def menu_dev() -> int: + last = 0 + while True: + choice = sub_choice("Dev serwery", ["api (tsx watch)", "app (vite)", "admin (vite)", "web (vite)"]) + if choice in ("", "0"): + return last + if choice in ("1", "2", "3", "4"): + last = cmd_dev(["api", "app", "admin", "web"][int(choice) - 1]) + return last + + +def menu_git() -> int: + last = 0 + while True: + choice = sub_choice("Git", ["status (krótki)", "log (ostatnie 15)", "unpushed", "fetch --prune", "pull --ff-only"]) + if choice in ("", "0"): + return last + mapping = {"1": "status", "2": "log", "3": "unpushed", "4": "fetch", "5": "pull"} + if choice in mapping: + last = cmd_git(mapping[choice]) + return last + + +MENU_HANDLERS = { + "status": cmd_summary, + "check": cmd_check, + "lint": menu_lint, + "testy": menu_tests, + "stack": menu_stack, + "dev": menu_dev, + "db": menu_db, + "deploy": menu_deploy, + "git": menu_git, + "env": cmd_envcheck, +} + + +def interactive() -> int: + last = 0 + while True: + print("\n" + c("FitOS — narzędzia", "1;36") + c(f" ({REPO_ROOT.name})", "90")) + for i, (_key, desc) in enumerate(MAIN_MENU, 1): + print(f" {i:>2}) {desc}") + print(" 0) exit") + try: + choice = input(c("> ", "1")).strip().lower() + except (EOFError, KeyboardInterrupt): + print() + return last + if choice in ("", "0", "q", "exit", "quit"): + return last + if choice.isdigit() and 1 <= int(choice) <= len(MAIN_MENU): + last = MENU_HANDLERS[MAIN_MENU[int(choice) - 1][0]]() + + +# --- CLI ---------------------------------------------------------------------------- + +def main() -> int: + parser = argparse.ArgumentParser(prog="fitos", description="Narzędzia FitOS (menu albo tryb CLI).") + sub = parser.add_subparsers(dest="cmd") + sub.add_parser("status", help="podsumowanie git+docker+health") + sub.add_parser("check", help="guard + lint + format + unit testy") + sub.add_parser("guard", help="strażnik liter PL (i18n)") + sub.add_parser("env", help="kontrola środowiska") + p = sub.add_parser("lint"); p.add_argument("packages", nargs="*", default=[]); p.add_argument("--fix", action="store_true") + p = sub.add_parser("format"); p.add_argument("packages", nargs="*", default=[]); p.add_argument("--check", action="store_true") + p = sub.add_parser("test"); p.add_argument("kind", choices=["unit", "e2e", "e2e:install"]); p.add_argument("packages", nargs="*", default=[]) + p = sub.add_parser("up"); p.add_argument("packages", nargs="*", default=[]) + p = sub.add_parser("rebuild"); p.add_argument("packages", nargs="*", default=[]) + p = sub.add_parser("down") + p = sub.add_parser("logs"); p.add_argument("service"); p.add_argument("--tail", type=int, default=100); p.add_argument("-f", "--follow", action="store_true") + p = sub.add_parser("restart"); p.add_argument("service") + p = sub.add_parser("ps") + p = sub.add_parser("backup") + p = sub.add_parser("prisma"); p.add_argument("action", choices=["format", "migrate", "generate", "seed", "studio"]) + p = sub.add_parser("deploy"); p.add_argument("env", choices=["staging", "prod"]); p.add_argument("--ref", default="origin/main") + p = sub.add_parser("dev"); p.add_argument("pkg", choices=PACKAGES) + p = sub.add_parser("git"); p.add_argument("action", choices=["status", "log", "unpushed", "fetch", "pull"]) + args = parser.parse_args() + + if not args.cmd: + return interactive() + + def pkgs(arg: list[str]) -> list[str]: + return arg if arg else list(PACKAGES) + + table = { + "status": cmd_summary, "check": cmd_check, "guard": cmd_guard, "env": cmd_envcheck, + "lint": lambda: cmd_lint(pkgs(args.packages), fix=args.fix), + "format": lambda: cmd_format(pkgs(args.packages), check_only=args.check), + "test": lambda: cmd_tests(args.kind, pkgs(args.packages)), + "up": lambda: cmd_stack_up(pkgs(args.packages)), + "rebuild": lambda: cmd_stack_rebuild(pkgs(args.packages)), + "down": cmd_stack_down, "ps": cmd_ps, "backup": cmd_backup, + "logs": lambda: cmd_logs(args.service, args.tail, args.follow), + "restart": lambda: cmd_restart(args.service), + "prisma": lambda: cmd_prisma(args.action), + "deploy": lambda: cmd_deploy(args.env, args.ref, []), + "dev": lambda: cmd_dev(args.pkg), + "git": lambda: cmd_git(args.action), + } + return table[args.cmd]() + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + print() + sys.exit(130)