-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
253 lines (209 loc) · 8.32 KB
/
Copy pathinstall.py
File metadata and controls
253 lines (209 loc) · 8.32 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
#!/usr/bin/env python3
"""
Cross-platform installer for gois — sem privilégios de admin.
Funciona em macOS, Linux e Windows. Faz tudo em user-space:
1. Localiza Python 3.11+ (ou pede para o utilizador instalar via pyenv/python.org).
2. Cria `./.venv` no diretório do projeto.
3. Instala o `gois` em modo editable (com extras [dev]).
4. Copia `config.example.yaml` -> `config.yaml` e `.env.example` -> `.env` se faltarem.
5. Tenta `git submodule update --init --recursive` (se houver git).
6. Tenta `scripts/unify-stack.sh` em POSIX (vendor Hermes/OpenClaw) — opcional.
7. Cria atalhos de execução cross-platform:
- POSIX: ./run.sh
- Windows: run.bat
8. Imprime instruções finais.
Uso:
python3 install.py # instalação completa
python3 install.py --skip-vendor # pula submódulos/unify-stack
python3 install.py --no-dev # instala sem extras [dev]
Exit codes: 0 ok · 2 pré-requisitos faltando · 3 falha no pip
"""
from __future__ import annotations
import argparse
import os
import platform
import shutil
import subprocess
import sys
from pathlib import Path
PROJECT_DIR = Path(__file__).resolve().parent
VENV_DIR = PROJECT_DIR / ".venv"
IS_WINDOWS = os.name == "nt"
MIN_PY = (3, 11)
# ---------- helpers ----------------------------------------------------------
def c(msg: str, color: str = "36") -> None:
if sys.stdout.isatty() and not IS_WINDOWS:
print(f"\033[{color}m[install]\033[0m {msg}")
else:
print(f"[install] {msg}")
def info(msg: str) -> None: c(msg, "36")
def ok(msg: str) -> None: c(msg, "32")
def warn(msg: str) -> None: c(msg, "33")
def err(msg: str) -> None: c(msg, "31")
def run(cmd: list[str], **kw) -> int:
info("$ " + " ".join(str(x) for x in cmd))
return subprocess.call(cmd, **kw)
def find_python() -> str | None:
"""Procura um Python >= 3.11 sem exigir admin."""
candidates: list[list[str]] = []
if IS_WINDOWS:
candidates += [["py", "-3"], ["python"], ["python3"]]
else:
candidates += [["python3.13"], ["python3.12"], ["python3.11"], ["python3"], ["python"]]
for base in candidates:
exe = shutil.which(base[0])
if not exe:
continue
try:
out = subprocess.check_output(
base + ["-c", "import sys;print('%d.%d' % sys.version_info[:2])"],
stderr=subprocess.DEVNULL,
text=True,
).strip()
major, minor = (int(x) for x in out.split("."))
if (major, minor) >= MIN_PY:
# Return as a single shell-safe string when launcher uses 'py -3'
if base[0] == "py":
return exe + " -3"
return exe
except Exception:
continue
return None
def venv_python() -> Path:
if IS_WINDOWS:
return VENV_DIR / "Scripts" / "python.exe"
return VENV_DIR / "bin" / "python"
def ensure_venv(host_python: str) -> Path:
py = venv_python()
if py.exists():
info(f"venv já existe em {VENV_DIR.relative_to(PROJECT_DIR)}")
return py
info(f"criando venv em {VENV_DIR.relative_to(PROJECT_DIR)}")
cmd = host_python.split() + ["-m", "venv", str(VENV_DIR)]
if run(cmd) != 0:
err("falha ao criar venv (verifique se o módulo `venv` está disponível)")
if not IS_WINDOWS:
warn("em Debian/Ubuntu: instale `python3-venv` (apt install --user não existe; use pyenv ou peça ao admin)")
sys.exit(2)
return py
def pip_install(py: Path, dev: bool) -> None:
base = [str(py), "-m", "pip", "install", "--disable-pip-version-check"]
info("atualizando pip / setuptools / wheel")
if run(base + ["--upgrade", "pip", "setuptools", "wheel"]) != 0:
warn("upgrade do pip falhou — seguindo mesmo assim")
target = ".[dev]" if dev else "."
info(f"instalando gois ({target})")
if run(base + ["-e", target], cwd=str(PROJECT_DIR)) != 0:
err("pip install falhou")
sys.exit(3)
def ensure_file(src: Path, dst: Path) -> None:
if dst.exists():
return
if not src.exists():
warn(f"{src.name} ausente — pulando")
return
shutil.copyfile(src, dst)
try:
if not IS_WINDOWS and dst.name == ".env":
os.chmod(dst, 0o600)
except OSError:
pass
ok(f"criado {dst.name} a partir de {src.name}")
def ensure_configs() -> None:
ensure_file(PROJECT_DIR / "config.example.yaml", PROJECT_DIR / "config.yaml")
ensure_file(PROJECT_DIR / ".env.example", PROJECT_DIR / ".env")
def init_submodules() -> None:
if not (PROJECT_DIR / ".gitmodules").exists():
return
git = shutil.which("git")
if not git:
warn("git não encontrado no PATH — submódulos não inicializados")
return
info("git submodule update --init --recursive")
if run([git, "submodule", "update", "--init", "--recursive"], cwd=str(PROJECT_DIR)) != 0:
warn("falha ao inicializar submódulos (siga sem vendor stack)")
def run_unify_stack() -> None:
script = PROJECT_DIR / "scripts" / "unify-stack.sh"
if IS_WINDOWS or not script.exists():
if IS_WINDOWS:
warn("unify-stack.sh é POSIX-only — em Windows use WSL2 para a stack vendor completa")
return
bash = shutil.which("bash")
if not bash:
warn("bash não encontrado — pulando unify-stack.sh")
return
if run([bash, str(script)], cwd=str(PROJECT_DIR)) != 0:
warn("unify-stack.sh falhou — gois funciona, mas Hermes/OpenClaw podem ficar incompletos")
def write_launchers() -> None:
py = venv_python()
if IS_WINDOWS:
bat = PROJECT_DIR / "run.bat"
bat.write_text(
"@echo off\r\n"
f'cd /d "%~dp0"\r\n'
f'"{py}" -m gois --config "%~dp0config.yaml" --env-file "%~dp0.env" %*\r\n',
encoding="utf-8",
)
ok("criado run.bat")
else:
sh = PROJECT_DIR / "run.sh"
sh.write_text(
"#!/usr/bin/env bash\n"
'set -euo pipefail\n'
'cd "$(dirname "$0")"\n'
f'exec "{py}" -m gois --config ./config.yaml --env-file ./.env "$@"\n'
)
os.chmod(sh, 0o755)
ok("criado run.sh (executável)")
def print_summary() -> None:
py = venv_python()
launcher = "run.bat" if IS_WINDOWS else "./run.sh"
print()
ok("instalação concluída.")
print(f" • venv: {VENV_DIR}")
print(f" • python: {py}")
print(f" • config: {PROJECT_DIR / 'config.yaml'}")
print(f" • secrets: {PROJECT_DIR / '.env'} (preencha DEEPSEEK_API_KEY / OPENAI_API_KEY)")
print()
print("Para iniciar:")
print(f" {launcher}")
print()
print("Ou (modo dev):")
if IS_WINDOWS:
print(f" {py} -m gois --config config.yaml")
else:
print(f" {py} -m gois --config config.yaml --env-file .env")
print()
print("Dashboard: http://127.0.0.1:9101/")
# ---------- main -------------------------------------------------------------
def main() -> int:
ap = argparse.ArgumentParser(description="Instalador cross-platform do gois (sem admin).")
ap.add_argument("--skip-vendor", action="store_true", help="não inicializa submódulos nem roda unify-stack.sh")
ap.add_argument("--no-dev", action="store_true", help="instala sem extras [dev]")
args = ap.parse_args()
info(f"sistema: {platform.system()} {platform.release()} ({platform.machine()})")
info(f"projeto: {PROJECT_DIR}")
host = find_python()
if not host:
err(f"Python {MIN_PY[0]}.{MIN_PY[1]}+ não encontrado.")
if IS_WINDOWS:
err("Instale (sem admin) via https://www.python.org/downloads/ marcando 'Install for me only'.")
elif platform.system() == "Darwin":
err("Instale via Homebrew (`brew install python@3.11`) ou pyenv (`curl https://pyenv.run | bash`).")
else:
err("Instale via pyenv (`curl https://pyenv.run | bash`) — não precisa de root.")
return 2
ok(f"python host: {host}")
ensure_venv(host)
pip_install(venv_python(), dev=not args.no_dev)
ensure_configs()
if not args.skip_vendor:
init_submodules()
run_unify_stack()
else:
info("--skip-vendor: pulando submódulos e unify-stack.sh")
write_launchers()
print_summary()
return 0
if __name__ == "__main__":
sys.exit(main())