776 lines
29 KiB
Python
776 lines
29 KiB
Python
#!/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:
|
|
if check_only and p == "api":
|
|
steps.append((f"format {p}", ["npx", "prettier", "--check", "src", "prisma"], REPO_ROOT / p))
|
|
continue
|
|
args = ["npm", "run", "format"]
|
|
if check_only:
|
|
args += ["--", "--check"]
|
|
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")
|
|
|
|
|
|
# --- auto-deploy staging (agent webhooka) -------------------------------------------------
|
|
|
|
def cmd_autodeploy(tail: int = 15) -> int:
|
|
"""Status agenta auto-deployu + ogon RELEASES.log. Nigdy nie failuje hard:
|
|
service i logi żyją na hoście staging; na maszynie dev pokazuje fallback SSH."""
|
|
head("Auto-deploy staging (agent webhooka na hoście)")
|
|
try:
|
|
proc = subprocess.run(["systemctl", "is-active", "fitos-deploy-agent"],
|
|
capture_output=True, text=True)
|
|
state = proc.stdout.strip() or "nieznany"
|
|
if proc.returncode == 0:
|
|
ok(f"fitos-deploy-agent: {state}")
|
|
else:
|
|
warn(f"fitos-deploy-agent: {state} (albo service zatrzymany, albo nie ta maszyna)")
|
|
except FileNotFoundError:
|
|
warn("brak systemctl lokalnie — agent mieszka na hoście staging (192.168.50.127)")
|
|
releases = Path.home() / "fitos-staging-agent" / "RELEASES.log"
|
|
if releases.is_file():
|
|
for line in releases.read_text(encoding="utf-8").splitlines()[-tail:]:
|
|
print(" " + line)
|
|
else:
|
|
info("podgląd historii z maszyny dev:")
|
|
info(" ssh homelab \"tail -n 15 ~/fitos-staging-agent/RELEASES.log\"")
|
|
info(" ssh homelab \"journalctl -u fitos-deploy-agent -n 50\"")
|
|
info("wyzwalacz: push do main na Gitei (repo Tisachi/FitOS) — awaryjnie: deploy.py / hostdeploy.py na hoście")
|
|
return 0
|
|
|
|
|
|
# --- 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)"),
|
|
("autodeploy", "Auto-deploy staging (status agenta + RELEASES.log)"),
|
|
("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,
|
|
"autodeploy": lambda: cmd_autodeploy(),
|
|
"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("autodeploy", help="status agenta auto-deployu + ogon RELEASES.log"); p.add_argument("--tail", type=int, default=15)
|
|
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, []),
|
|
"autodeploy": lambda: cmd_autodeploy(args.tail),
|
|
"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)
|