sofia-deploy 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sofia/__init__.py +7 -0
- sofia/__main__.py +4 -0
- sofia/build.py +59 -0
- sofia/cli.py +191 -0
- sofia/config.py +107 -0
- sofia/console.py +78 -0
- sofia/deploy.py +101 -0
- sofia/detect.py +141 -0
- sofia/nginx_setup.py +69 -0
- sofia/node_runtime.py +82 -0
- sofia/packages.py +72 -0
- sofia/ssl_setup.py +61 -0
- sofia/system.py +135 -0
- sofia/systemd_setup.py +52 -0
- sofia/templates/__init__.py +1 -0
- sofia/templates/app.service.tpl +20 -0
- sofia/templates/nginx-proxy-http.conf.tpl +24 -0
- sofia/templates/nginx-proxy-ssl.conf.tpl +45 -0
- sofia/templates/nginx-static-http.conf.tpl +18 -0
- sofia/templates/nginx-static-ssl.conf.tpl +36 -0
- sofia/templates/options-ssl-nginx.conf +6 -0
- sofia/templates_util.py +20 -0
- sofia_deploy-1.0.0.dist-info/METADATA +107 -0
- sofia_deploy-1.0.0.dist-info/RECORD +28 -0
- sofia_deploy-1.0.0.dist-info/WHEEL +5 -0
- sofia_deploy-1.0.0.dist-info/entry_points.txt +2 -0
- sofia_deploy-1.0.0.dist-info/licenses/LICENSE +21 -0
- sofia_deploy-1.0.0.dist-info/top_level.txt +1 -0
sofia/__init__.py
ADDED
sofia/__main__.py
ADDED
sofia/build.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import stat
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import console
|
|
8
|
+
from .config import DeployConfig
|
|
9
|
+
from .system import run
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _chown_tree(path: Path, user: str, group: str) -> None:
|
|
13
|
+
try:
|
|
14
|
+
import grp
|
|
15
|
+
import pwd
|
|
16
|
+
|
|
17
|
+
uid = pwd.getpwnam(user).pw_uid
|
|
18
|
+
gid = grp.getgrnam(group).gr_gid
|
|
19
|
+
except KeyError:
|
|
20
|
+
return
|
|
21
|
+
for root, dirs, files in os.walk(path):
|
|
22
|
+
try:
|
|
23
|
+
os.chown(root, uid, gid)
|
|
24
|
+
except FileNotFoundError:
|
|
25
|
+
continue
|
|
26
|
+
for name in dirs + files:
|
|
27
|
+
try:
|
|
28
|
+
os.chown(os.path.join(root, name), uid, gid)
|
|
29
|
+
except FileNotFoundError:
|
|
30
|
+
continue
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_app(cfg: DeployConfig) -> None:
|
|
34
|
+
app = cfg.app_dir
|
|
35
|
+
assert app is not None
|
|
36
|
+
console.log(f"Build dans {app}…")
|
|
37
|
+
_chown_tree(app, cfg.app_user, cfg.app_group)
|
|
38
|
+
|
|
39
|
+
if cfg.skip_build:
|
|
40
|
+
console.warn("skip_build — build ignoré")
|
|
41
|
+
else:
|
|
42
|
+
user = cfg.app_user if cfg.app_user != "root" else None
|
|
43
|
+
run(
|
|
44
|
+
["bash", "-lc", f"cd {shlex_path(app)} && {cfg.build_command}"],
|
|
45
|
+
user=user,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if cfg.serve_mode == "static":
|
|
49
|
+
index = cfg.static_path / "index.html"
|
|
50
|
+
if not index.exists():
|
|
51
|
+
console.die(
|
|
52
|
+
f"Build incomplet : {index} manquant. "
|
|
53
|
+
"Vérifiez static_root / build_command."
|
|
54
|
+
)
|
|
55
|
+
console.log(f"Static root OK : {cfg.static_path}")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def shlex_path(path: Path) -> str:
|
|
59
|
+
return str(path).replace("'", "'\\''")
|
sofia/cli.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import console
|
|
8
|
+
from .config import DeployConfig
|
|
9
|
+
from .deploy import deploy
|
|
10
|
+
from .detect import FRAMEWORKS, SERVE_MODES, detect_project
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _load_env(path: Path) -> dict[str, str]:
|
|
14
|
+
data: dict[str, str] = {}
|
|
15
|
+
if not path.exists():
|
|
16
|
+
return data
|
|
17
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
18
|
+
line = line.strip()
|
|
19
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
20
|
+
continue
|
|
21
|
+
k, v = line.split("=", 1)
|
|
22
|
+
data[k.strip()] = v.strip().strip('"').strip("'")
|
|
23
|
+
return data
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def interactive_config(project_root: Path) -> DeployConfig:
|
|
27
|
+
console.title("Sofia — déploiement interactif")
|
|
28
|
+
print("À lancer sur le serveur cible (SSH + sudo).\n")
|
|
29
|
+
|
|
30
|
+
root = Path(console.ask("Chemin du projet", str(project_root)))
|
|
31
|
+
hints = detect_project(root)
|
|
32
|
+
saved = _load_env(root / "sofia.env")
|
|
33
|
+
|
|
34
|
+
console.log(
|
|
35
|
+
f"Détecté : {hints.framework} · mode {hints.serve_mode} · dir {hints.app_dir}"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
app_name = console.ask("Nom de l'app (service systemd)", saved.get("APP_NAME") or root.name)
|
|
39
|
+
domain = console.ask("Domaine", saved.get("DOMAIN") or "example.com")
|
|
40
|
+
www = console.ask("Domaine www", saved.get("WWW_DOMAIN") or f"www.{domain.removeprefix('www.')}")
|
|
41
|
+
|
|
42
|
+
framework = console.ask_choice(
|
|
43
|
+
"Framework",
|
|
44
|
+
list(FRAMEWORKS),
|
|
45
|
+
saved.get("FRAMEWORK") or hints.framework,
|
|
46
|
+
)
|
|
47
|
+
serve_mode = console.ask_choice(
|
|
48
|
+
"Mode de service",
|
|
49
|
+
list(SERVE_MODES),
|
|
50
|
+
saved.get("SERVE_MODE") or hints.serve_mode,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
app_dir = Path(console.ask("Dossier de l'app (package.json)", saved.get("APP_DIR") or str(hints.app_dir)))
|
|
54
|
+
build_command = console.ask("Commande de build", saved.get("BUILD_COMMAND") or hints.build_command)
|
|
55
|
+
|
|
56
|
+
start_command = saved.get("START_COMMAND") or hints.start_command
|
|
57
|
+
static_root = saved.get("STATIC_ROOT") or hints.static_root
|
|
58
|
+
port = int(saved.get("PORT") or "3000")
|
|
59
|
+
|
|
60
|
+
if serve_mode == "node":
|
|
61
|
+
start_command = console.ask("Commande de démarrage", start_command or "npm start")
|
|
62
|
+
port = int(console.ask("Port interne", str(port)))
|
|
63
|
+
else:
|
|
64
|
+
static_root = console.ask("Dossier des fichiers statiques (relatif à l'app)", static_root or "dist")
|
|
65
|
+
|
|
66
|
+
enable_ssl = console.ask_bool(
|
|
67
|
+
"Activer HTTPS (Let's Encrypt) ?",
|
|
68
|
+
saved.get("ENABLE_SSL", "true").lower() != "false",
|
|
69
|
+
)
|
|
70
|
+
email = saved.get("EMAIL", "")
|
|
71
|
+
if enable_ssl:
|
|
72
|
+
email = console.ask("Email Let's Encrypt", email or None)
|
|
73
|
+
|
|
74
|
+
admin_password = saved.get("ADMIN_PASSWORD", "")
|
|
75
|
+
if console.ask_bool("Définir ADMIN_PASSWORD (apps type BrainUp) ?", bool(admin_password)):
|
|
76
|
+
if admin_password and console.ask_bool("Réutiliser le mot de passe enregistré ?", True):
|
|
77
|
+
pass
|
|
78
|
+
else:
|
|
79
|
+
admin_password = console.ask("ADMIN_PASSWORD", secret=True)
|
|
80
|
+
|
|
81
|
+
skip_build = not console.ask_bool("Lancer le build maintenant ?", True)
|
|
82
|
+
app_user = console.ask(
|
|
83
|
+
"Utilisateur système",
|
|
84
|
+
os.environ.get("SUDO_USER") or os.environ.get("USER") or "ec2-user",
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
print()
|
|
88
|
+
console.title("Récapitulatif")
|
|
89
|
+
print(f" app : {app_name}")
|
|
90
|
+
print(f" framework : {framework} / {serve_mode}")
|
|
91
|
+
print(f" root : {root}")
|
|
92
|
+
print(f" app_dir : {app_dir}")
|
|
93
|
+
print(f" domain : {domain}")
|
|
94
|
+
print(f" SSL : {'oui' if enable_ssl else 'non'}")
|
|
95
|
+
print(f" build : {build_command}")
|
|
96
|
+
if serve_mode == "node":
|
|
97
|
+
print(f" start : {start_command} (:{port})")
|
|
98
|
+
else:
|
|
99
|
+
print(f" static : {static_root}")
|
|
100
|
+
print()
|
|
101
|
+
if not console.ask_bool("Confirmer le déploiement ?", True):
|
|
102
|
+
console.warn("Annulé.")
|
|
103
|
+
raise SystemExit(0)
|
|
104
|
+
|
|
105
|
+
return DeployConfig(
|
|
106
|
+
project_root=root,
|
|
107
|
+
app_name=app_name,
|
|
108
|
+
domain=domain,
|
|
109
|
+
www_domain=www,
|
|
110
|
+
email=email,
|
|
111
|
+
port=port,
|
|
112
|
+
framework=framework,
|
|
113
|
+
serve_mode=serve_mode,
|
|
114
|
+
app_dir=app_dir,
|
|
115
|
+
build_command=build_command,
|
|
116
|
+
start_command=start_command,
|
|
117
|
+
static_root=static_root,
|
|
118
|
+
enable_ssl=enable_ssl,
|
|
119
|
+
skip_build=skip_build,
|
|
120
|
+
app_user=app_user,
|
|
121
|
+
admin_password=admin_password,
|
|
122
|
+
token_secret=saved.get("TOKEN_SECRET", ""),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def config_from_env(project_root: Path, env: dict[str, str], *, skip_ssl: bool, skip_build: bool) -> DeployConfig:
|
|
127
|
+
enable_ssl = env.get("ENABLE_SSL", "true").lower() != "false" and not skip_ssl
|
|
128
|
+
if not env.get("DOMAIN"):
|
|
129
|
+
console.die("DOMAIN manquant dans sofia.env")
|
|
130
|
+
if enable_ssl and not env.get("EMAIL"):
|
|
131
|
+
console.die("EMAIL manquant dans sofia.env")
|
|
132
|
+
return DeployConfig(
|
|
133
|
+
project_root=project_root,
|
|
134
|
+
app_name=env.get("APP_NAME") or project_root.name,
|
|
135
|
+
domain=env["DOMAIN"],
|
|
136
|
+
www_domain=env.get("WWW_DOMAIN", ""),
|
|
137
|
+
email=env.get("EMAIL", ""),
|
|
138
|
+
port=int(env.get("PORT", "3000")),
|
|
139
|
+
framework=env.get("FRAMEWORK", "node"),
|
|
140
|
+
serve_mode=env.get("SERVE_MODE", "node"),
|
|
141
|
+
app_dir=Path(env["APP_DIR"]) if env.get("APP_DIR") else None,
|
|
142
|
+
build_command=env.get("BUILD_COMMAND", "npm ci || npm install"),
|
|
143
|
+
start_command=env.get("START_COMMAND", "npm start"),
|
|
144
|
+
static_root=env.get("STATIC_ROOT", "dist"),
|
|
145
|
+
enable_ssl=enable_ssl,
|
|
146
|
+
skip_build=skip_build,
|
|
147
|
+
admin_password=env.get("ADMIN_PASSWORD", ""),
|
|
148
|
+
token_secret=env.get("TOKEN_SECRET", ""),
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def main(argv: list[str] | None = None) -> int:
|
|
153
|
+
parser = argparse.ArgumentParser(
|
|
154
|
+
prog="sofia",
|
|
155
|
+
description="Sofia — déploiement interactif Angular / React / Vite / Node.",
|
|
156
|
+
)
|
|
157
|
+
parser.add_argument("--repo", "--project", dest="project", type=Path, help="Chemin du projet")
|
|
158
|
+
parser.add_argument("--config", type=Path, help="Fichier sofia.env")
|
|
159
|
+
parser.add_argument("--non-interactive", action="store_true")
|
|
160
|
+
parser.add_argument("--skip-ssl", action="store_true")
|
|
161
|
+
parser.add_argument("--skip-build", action="store_true")
|
|
162
|
+
args = parser.parse_args(argv)
|
|
163
|
+
|
|
164
|
+
project = (args.project or Path.cwd()).resolve()
|
|
165
|
+
env_path = args.config or (project / "sofia.env")
|
|
166
|
+
env = _load_env(env_path)
|
|
167
|
+
|
|
168
|
+
if args.non_interactive:
|
|
169
|
+
if not env:
|
|
170
|
+
console.die(f"--non-interactive : config introuvable ({env_path})")
|
|
171
|
+
cfg = config_from_env(project, env, skip_ssl=args.skip_ssl, skip_build=args.skip_build)
|
|
172
|
+
else:
|
|
173
|
+
cfg = interactive_config(project)
|
|
174
|
+
if args.skip_ssl:
|
|
175
|
+
cfg.enable_ssl = False
|
|
176
|
+
if args.skip_build:
|
|
177
|
+
cfg.skip_build = True
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
deploy(cfg)
|
|
181
|
+
except KeyboardInterrupt:
|
|
182
|
+
console.warn("Interrompu.")
|
|
183
|
+
return 130
|
|
184
|
+
except Exception as exc: # noqa: BLE001
|
|
185
|
+
console.error(str(exc))
|
|
186
|
+
return 1
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
raise SystemExit(main())
|
sofia/config.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import grp
|
|
4
|
+
import os
|
|
5
|
+
import pwd
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _slug(name: str) -> str:
|
|
13
|
+
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
|
|
14
|
+
return slug or "app"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class DeployConfig:
|
|
19
|
+
project_root: Path
|
|
20
|
+
app_name: str = ""
|
|
21
|
+
domain: str = ""
|
|
22
|
+
www_domain: str = ""
|
|
23
|
+
email: str = ""
|
|
24
|
+
port: int = 3000
|
|
25
|
+
framework: str = "node" # angular | react | vite | node
|
|
26
|
+
serve_mode: str = "node" # node | static
|
|
27
|
+
app_dir: Path | None = None
|
|
28
|
+
build_command: str = "npm ci || npm install"
|
|
29
|
+
start_command: str = "npm start"
|
|
30
|
+
static_root: str = "dist"
|
|
31
|
+
enable_ssl: bool = True
|
|
32
|
+
skip_build: bool = False
|
|
33
|
+
app_user: str = ""
|
|
34
|
+
app_group: str = ""
|
|
35
|
+
node_bin: str = ""
|
|
36
|
+
node_version: str = "20.18.2"
|
|
37
|
+
env_vars: dict[str, str] = field(default_factory=dict)
|
|
38
|
+
# optional secrets commonly needed
|
|
39
|
+
admin_password: str = ""
|
|
40
|
+
token_secret: str = ""
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
self.project_root = Path(self.project_root).resolve()
|
|
44
|
+
if self.app_dir is None:
|
|
45
|
+
self.app_dir = self.project_root
|
|
46
|
+
else:
|
|
47
|
+
self.app_dir = Path(self.app_dir).resolve()
|
|
48
|
+
if not self.app_name:
|
|
49
|
+
self.app_name = _slug(self.project_root.name)
|
|
50
|
+
else:
|
|
51
|
+
self.app_name = _slug(self.app_name)
|
|
52
|
+
if not self.www_domain and self.domain:
|
|
53
|
+
self.www_domain = f"www.{self.domain.removeprefix('www.')}"
|
|
54
|
+
if not self.token_secret:
|
|
55
|
+
self.token_secret = secrets.token_hex(32)
|
|
56
|
+
if not self.app_user:
|
|
57
|
+
candidate = os.environ.get("SUDO_USER") or os.environ.get("USER") or "ec2-user"
|
|
58
|
+
try:
|
|
59
|
+
pwd.getpwnam(candidate)
|
|
60
|
+
self.app_user = candidate
|
|
61
|
+
except KeyError:
|
|
62
|
+
self.app_user = "root"
|
|
63
|
+
if not self.app_group:
|
|
64
|
+
try:
|
|
65
|
+
gid = pwd.getpwnam(self.app_user).pw_gid
|
|
66
|
+
self.app_group = grp.getgrgid(gid).gr_name
|
|
67
|
+
except KeyError:
|
|
68
|
+
self.app_group = "root"
|
|
69
|
+
# Inject common env
|
|
70
|
+
self.env_vars.setdefault("NODE_ENV", "production")
|
|
71
|
+
self.env_vars.setdefault("PORT", str(self.port))
|
|
72
|
+
if self.admin_password:
|
|
73
|
+
self.env_vars.setdefault("ADMIN_PASSWORD", self.admin_password)
|
|
74
|
+
if self.token_secret:
|
|
75
|
+
self.env_vars.setdefault("TOKEN_SECRET", self.token_secret)
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def service_name(self) -> str:
|
|
79
|
+
return self.app_name
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def env_system(self) -> Path:
|
|
83
|
+
return Path(f"/etc/sofia/{self.app_name}/env")
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def nginx_site(self) -> str:
|
|
87
|
+
return self.app_name
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def static_path(self) -> Path:
|
|
91
|
+
return (self.app_dir / self.static_root).resolve()
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def config_local(self) -> Path:
|
|
95
|
+
return self.project_root / "sofia.env"
|
|
96
|
+
|
|
97
|
+
def validate(self) -> None:
|
|
98
|
+
if not self.domain:
|
|
99
|
+
raise ValueError("domain obligatoire")
|
|
100
|
+
if self.enable_ssl and not self.email:
|
|
101
|
+
raise ValueError("email obligatoire si SSL activé")
|
|
102
|
+
if not self.app_dir or not self.app_dir.is_dir():
|
|
103
|
+
raise ValueError(f"app_dir introuvable : {self.app_dir}")
|
|
104
|
+
if self.serve_mode not in {"node", "static"}:
|
|
105
|
+
raise ValueError("serve_mode doit être 'node' ou 'static'")
|
|
106
|
+
if self.serve_mode == "node" and not self.start_command:
|
|
107
|
+
raise ValueError("start_command obligatoire en mode node")
|
sofia/console.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import getpass
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Colors:
|
|
8
|
+
GREEN = "\033[0;32m"
|
|
9
|
+
YELLOW = "\033[1;33m"
|
|
10
|
+
RED = "\033[0;31m"
|
|
11
|
+
CYAN = "\033[0;36m"
|
|
12
|
+
BOLD = "\033[1m"
|
|
13
|
+
NC = "\033[0m"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _c(color: str, msg: str) -> str:
|
|
17
|
+
if not sys.stdout.isatty():
|
|
18
|
+
return msg
|
|
19
|
+
return f"{color}{msg}{Colors.NC}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def log(msg: str) -> None:
|
|
23
|
+
print(_c(Colors.GREEN, "[sofia] ") + msg)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def warn(msg: str) -> None:
|
|
27
|
+
print(_c(Colors.YELLOW, "[sofia] ") + msg)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def error(msg: str) -> None:
|
|
31
|
+
print(_c(Colors.RED, "[sofia] ") + msg, file=sys.stderr)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def die(msg: str) -> None:
|
|
35
|
+
error(msg)
|
|
36
|
+
raise SystemExit(1)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def title(msg: str) -> None:
|
|
40
|
+
print()
|
|
41
|
+
print(_c(Colors.BOLD + Colors.CYAN, msg))
|
|
42
|
+
print(_c(Colors.CYAN, "=" * max(len(msg), 8)))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ask(prompt: str, default: str | None = None, *, secret: bool = False) -> str:
|
|
46
|
+
suffix = f" [{default}]" if default not in (None, "") else ""
|
|
47
|
+
label = f"{prompt}{suffix}: "
|
|
48
|
+
while True:
|
|
49
|
+
value = getpass.getpass(label) if secret else input(label).strip()
|
|
50
|
+
if not value and default is not None:
|
|
51
|
+
return default
|
|
52
|
+
if value:
|
|
53
|
+
return value
|
|
54
|
+
print(" → valeur obligatoire.")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def ask_bool(prompt: str, default: bool = True) -> bool:
|
|
58
|
+
hint = "O/n" if default else "o/N"
|
|
59
|
+
while True:
|
|
60
|
+
value = input(f"{prompt} [{hint}]: ").strip().lower()
|
|
61
|
+
if not value:
|
|
62
|
+
return default
|
|
63
|
+
if value in {"o", "oui", "y", "yes", "1", "true"}:
|
|
64
|
+
return True
|
|
65
|
+
if value in {"n", "non", "no", "0", "false"}:
|
|
66
|
+
return False
|
|
67
|
+
print(" → répondre par o/n.")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def ask_choice(prompt: str, choices: list[str], default: str) -> str:
|
|
71
|
+
labels = "/".join(f"[{c}]" if c == default else c for c in choices)
|
|
72
|
+
while True:
|
|
73
|
+
value = input(f"{prompt} ({labels}): ").strip().lower()
|
|
74
|
+
if not value:
|
|
75
|
+
return default
|
|
76
|
+
if value in choices:
|
|
77
|
+
return value
|
|
78
|
+
print(f" → choisir parmi : {', '.join(choices)}")
|
sofia/deploy.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.request
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import console
|
|
8
|
+
from .build import build_app
|
|
9
|
+
from .config import DeployConfig
|
|
10
|
+
from .nginx_setup import install_nginx_http
|
|
11
|
+
from .node_runtime import ensure_node
|
|
12
|
+
from .packages import install_base_packages
|
|
13
|
+
from .ssl_setup import obtain_ssl
|
|
14
|
+
from .system import HostOS, open_firewall, require_root
|
|
15
|
+
from .systemd_setup import install_systemd
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def write_runtime_env(cfg: DeployConfig) -> None:
|
|
19
|
+
console.log(f"Écriture de {cfg.env_system}")
|
|
20
|
+
cfg.env_system.parent.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
lines = [f"{k}={v}" for k, v in sorted(cfg.env_vars.items())]
|
|
22
|
+
cfg.env_system.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
23
|
+
cfg.env_system.chmod(0o600)
|
|
24
|
+
|
|
25
|
+
if not cfg.config_local.exists():
|
|
26
|
+
local = {
|
|
27
|
+
"APP_NAME": cfg.app_name,
|
|
28
|
+
"DOMAIN": cfg.domain,
|
|
29
|
+
"WWW_DOMAIN": cfg.www_domain,
|
|
30
|
+
"EMAIL": cfg.email,
|
|
31
|
+
"PORT": str(cfg.port),
|
|
32
|
+
"FRAMEWORK": cfg.framework,
|
|
33
|
+
"SERVE_MODE": cfg.serve_mode,
|
|
34
|
+
"APP_DIR": str(cfg.app_dir),
|
|
35
|
+
"BUILD_COMMAND": cfg.build_command,
|
|
36
|
+
"START_COMMAND": cfg.start_command,
|
|
37
|
+
"STATIC_ROOT": cfg.static_root,
|
|
38
|
+
"ENABLE_SSL": "true" if cfg.enable_ssl else "false",
|
|
39
|
+
"ADMIN_PASSWORD": cfg.admin_password,
|
|
40
|
+
"TOKEN_SECRET": cfg.token_secret,
|
|
41
|
+
}
|
|
42
|
+
cfg.config_local.write_text(
|
|
43
|
+
"\n".join(f"{k}={v}" for k, v in local.items()) + "\n",
|
|
44
|
+
encoding="utf-8",
|
|
45
|
+
)
|
|
46
|
+
cfg.config_local.chmod(0o600)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def healthcheck(cfg: DeployConfig) -> None:
|
|
50
|
+
console.log("Vérification…")
|
|
51
|
+
if cfg.serve_mode == "node":
|
|
52
|
+
url = f"http://127.0.0.1:{cfg.port}/"
|
|
53
|
+
try:
|
|
54
|
+
with urllib.request.urlopen(url, timeout=5) as resp: # noqa: S310
|
|
55
|
+
code = resp.getcode()
|
|
56
|
+
except (urllib.error.URLError, TimeoutError):
|
|
57
|
+
code = "ERR"
|
|
58
|
+
if code in {200, 304}:
|
|
59
|
+
console.log(f"App OK sur :{cfg.port} (HTTP {code})")
|
|
60
|
+
else:
|
|
61
|
+
console.warn(
|
|
62
|
+
f"HTTP {code} sur :{cfg.port} — journalctl -u {cfg.service_name} -n 50"
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
index = cfg.static_path / "index.html"
|
|
66
|
+
if index.exists():
|
|
67
|
+
console.log(f"Fichiers statiques OK ({cfg.static_path})")
|
|
68
|
+
else:
|
|
69
|
+
console.warn(f"index.html manquant dans {cfg.static_path}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def print_summary(cfg: DeployConfig) -> None:
|
|
73
|
+
print()
|
|
74
|
+
console.log("===== Déploiement terminé =====")
|
|
75
|
+
scheme = "https" if cfg.enable_ssl else "http"
|
|
76
|
+
print(f" App : {cfg.app_name} ({cfg.framework} / {cfg.serve_mode})")
|
|
77
|
+
print(f" URL : {scheme}://{cfg.domain}")
|
|
78
|
+
if cfg.serve_mode == "node":
|
|
79
|
+
print(f" Service : systemctl status {cfg.service_name}")
|
|
80
|
+
print(f" Logs : journalctl -u {cfg.service_name} -f")
|
|
81
|
+
print(f" Env : {cfg.env_system}")
|
|
82
|
+
print()
|
|
83
|
+
console.warn(f"DNS A/AAAA de {cfg.domain} → IP de ce serveur (ports 80/443).")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def deploy(cfg: DeployConfig) -> None:
|
|
87
|
+
"""Deploy the project on the current Linux host (requires root)."""
|
|
88
|
+
require_root()
|
|
89
|
+
cfg.validate()
|
|
90
|
+
host = HostOS()
|
|
91
|
+
|
|
92
|
+
install_base_packages(host)
|
|
93
|
+
cfg.node_bin = ensure_node(cfg, host)
|
|
94
|
+
open_firewall()
|
|
95
|
+
write_runtime_env(cfg)
|
|
96
|
+
build_app(cfg)
|
|
97
|
+
install_systemd(cfg)
|
|
98
|
+
install_nginx_http(cfg)
|
|
99
|
+
obtain_ssl(cfg)
|
|
100
|
+
healthcheck(cfg)
|
|
101
|
+
print_summary(cfg)
|
sofia/detect.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
FRAMEWORKS = ("angular", "react", "vite", "node")
|
|
9
|
+
SERVE_MODES = ("static", "node")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ProjectHints:
|
|
14
|
+
framework: str
|
|
15
|
+
serve_mode: str
|
|
16
|
+
app_dir: Path
|
|
17
|
+
build_command: str
|
|
18
|
+
start_command: str
|
|
19
|
+
static_root: str
|
|
20
|
+
package_manager: str # npm | pnpm | yarn
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _read_package_json(path: Path) -> dict:
|
|
24
|
+
pkg = path / "package.json"
|
|
25
|
+
if not pkg.exists():
|
|
26
|
+
return {}
|
|
27
|
+
try:
|
|
28
|
+
return json.loads(pkg.read_text(encoding="utf-8"))
|
|
29
|
+
except json.JSONDecodeError:
|
|
30
|
+
return {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _pm(app_dir: Path) -> str:
|
|
34
|
+
if (app_dir / "pnpm-lock.yaml").exists():
|
|
35
|
+
return "pnpm"
|
|
36
|
+
if (app_dir / "yarn.lock").exists():
|
|
37
|
+
return "yarn"
|
|
38
|
+
return "npm"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _install_cmd(pm: str) -> str:
|
|
42
|
+
return {"npm": "npm ci || npm install", "pnpm": "pnpm install --frozen-lockfile || pnpm install", "yarn": "yarn install --frozen-lockfile || yarn install"}[pm]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def find_app_dir(project_root: Path) -> Path:
|
|
46
|
+
"""Prefer project_root, else common subfolders with package.json."""
|
|
47
|
+
root = project_root.resolve()
|
|
48
|
+
if (root / "package.json").exists():
|
|
49
|
+
return root
|
|
50
|
+
for name in ("backend", "frontend", "web", "app", "client", "server"):
|
|
51
|
+
candidate = root / name
|
|
52
|
+
if (candidate / "package.json").exists():
|
|
53
|
+
return candidate
|
|
54
|
+
return root
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def detect_project(project_root: Path) -> ProjectHints:
|
|
58
|
+
app_dir = find_app_dir(project_root)
|
|
59
|
+
data = _read_package_json(app_dir)
|
|
60
|
+
deps = {**(data.get("dependencies") or {}), **(data.get("devDependencies") or {})}
|
|
61
|
+
scripts = data.get("scripts") or {}
|
|
62
|
+
pm = _pm(app_dir)
|
|
63
|
+
install = _install_cmd(pm)
|
|
64
|
+
|
|
65
|
+
has_angular = "@angular/core" in deps or "@angular/cli" in deps
|
|
66
|
+
has_vite = "vite" in deps
|
|
67
|
+
has_react = "react" in deps
|
|
68
|
+
has_next = "next" in deps
|
|
69
|
+
|
|
70
|
+
# Node server entry candidates
|
|
71
|
+
server_candidates = [
|
|
72
|
+
app_dir / "server" / "server.js",
|
|
73
|
+
app_dir / "server.js",
|
|
74
|
+
app_dir / "src" / "server.js",
|
|
75
|
+
app_dir / "index.js",
|
|
76
|
+
]
|
|
77
|
+
has_server_file = any(p.exists() for p in server_candidates)
|
|
78
|
+
start_script = scripts.get("start") or scripts.get("server") or scripts.get("prod")
|
|
79
|
+
|
|
80
|
+
if has_angular:
|
|
81
|
+
framework = "angular"
|
|
82
|
+
build = f"{install} && npx ng build --configuration production"
|
|
83
|
+
# Angular with custom Node server (BrainUp-style) vs pure static
|
|
84
|
+
if has_server_file or (start_script and "node" in str(start_script)):
|
|
85
|
+
serve_mode = "node"
|
|
86
|
+
start = start_script or "node server/server.js"
|
|
87
|
+
# Prefer explicit file if scripts unclear
|
|
88
|
+
for p in server_candidates:
|
|
89
|
+
if p.exists():
|
|
90
|
+
start = f"node {p.relative_to(app_dir)}"
|
|
91
|
+
break
|
|
92
|
+
static_root = ""
|
|
93
|
+
else:
|
|
94
|
+
serve_mode = "static"
|
|
95
|
+
start = ""
|
|
96
|
+
# Angular 17+ application builder → dist/<name>/browser
|
|
97
|
+
dist = app_dir / "dist"
|
|
98
|
+
static_root = "dist"
|
|
99
|
+
if dist.is_dir():
|
|
100
|
+
browsers = list(dist.glob("*/browser"))
|
|
101
|
+
if browsers:
|
|
102
|
+
static_root = str(browsers[0].relative_to(app_dir))
|
|
103
|
+
else:
|
|
104
|
+
subs = [p for p in dist.iterdir() if p.is_dir()]
|
|
105
|
+
if len(subs) == 1:
|
|
106
|
+
static_root = str(subs[0].relative_to(app_dir))
|
|
107
|
+
elif has_next:
|
|
108
|
+
framework = "node"
|
|
109
|
+
serve_mode = "node"
|
|
110
|
+
build = f"{install} && {pm} run build"
|
|
111
|
+
start = start_script or f"{pm} start"
|
|
112
|
+
static_root = ""
|
|
113
|
+
elif has_vite:
|
|
114
|
+
framework = "vite"
|
|
115
|
+
serve_mode = "static"
|
|
116
|
+
build = f"{install} && {pm} run build"
|
|
117
|
+
start = ""
|
|
118
|
+
static_root = "dist"
|
|
119
|
+
elif has_react:
|
|
120
|
+
framework = "react"
|
|
121
|
+
serve_mode = "static"
|
|
122
|
+
build = f"{install} && {pm} run build"
|
|
123
|
+
start = ""
|
|
124
|
+
# CRA → build/, Vite-react already caught above
|
|
125
|
+
static_root = "build" if (app_dir / "build").exists() or "react-scripts" in deps else "dist"
|
|
126
|
+
else:
|
|
127
|
+
framework = "node"
|
|
128
|
+
serve_mode = "node"
|
|
129
|
+
build = f"{install}" + (f" && {pm} run build" if "build" in scripts else "")
|
|
130
|
+
start = start_script or ("node server.js" if (app_dir / "server.js").exists() else f"{pm} start")
|
|
131
|
+
static_root = ""
|
|
132
|
+
|
|
133
|
+
return ProjectHints(
|
|
134
|
+
framework=framework,
|
|
135
|
+
serve_mode=serve_mode,
|
|
136
|
+
app_dir=app_dir,
|
|
137
|
+
build_command=build,
|
|
138
|
+
start_command=start,
|
|
139
|
+
static_root=static_root,
|
|
140
|
+
package_manager=pm,
|
|
141
|
+
)
|