215 lines
6.8 KiB
Python
215 lines
6.8 KiB
Python
|
|
#!/usr/bin/python3
|
||
|
|
# Deploy: lädt die Web-App (public, src, views, storage, bin) per FTPS auf den Server.
|
||
|
|
# Zugangsdaten werden aus ../motorradig/.credentials gelesen (FTP_URL, FTP_USER, FTP_PASSWORD).
|
||
|
|
|
||
|
|
import argparse
|
||
|
|
import ftplib
|
||
|
|
import io
|
||
|
|
import os
|
||
|
|
import sys
|
||
|
|
|
||
|
|
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||
|
|
APP_ROOT = os.path.normpath(os.path.join(TOOLS_DIR, '..', 'motorradig'))
|
||
|
|
CRED_FILE = os.path.join(APP_ROOT, '.credentials')
|
||
|
|
|
||
|
|
REMOTE_BASE = '/motorradig'
|
||
|
|
|
||
|
|
# Nur diese Verzeichnisse werden hochgeladen (Rest: .git, *.sql, Docker, .env, .credentials …).
|
||
|
|
UPLOAD_DIRS = ['public', 'src', 'views', 'storage', 'bin']
|
||
|
|
|
||
|
|
# Media-Verzeichnis, das mit --skip-media ausgelassen wird.
|
||
|
|
MEDIA_REL = os.path.join('storage', 'img_storage')
|
||
|
|
|
||
|
|
# ANSI-Signalfarben
|
||
|
|
RESET = '\033[0m'
|
||
|
|
RED = '\033[1;31m'
|
||
|
|
YELLOW = '\033[1;33m'
|
||
|
|
GREEN = '\033[1;32m'
|
||
|
|
|
||
|
|
|
||
|
|
def load_credentials(path: str) -> dict:
|
||
|
|
creds = {}
|
||
|
|
if not os.path.isfile(path):
|
||
|
|
print(f"Fehler: Credentials-Datei nicht gefunden: {path}", file=sys.stderr)
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
with open(path, 'r', encoding='utf-8') as fh:
|
||
|
|
for line in fh:
|
||
|
|
line = line.strip()
|
||
|
|
if not line or line.startswith('#') or '=' not in line:
|
||
|
|
continue
|
||
|
|
key, value = line.split('=', 1)
|
||
|
|
creds[key.strip()] = value.strip()
|
||
|
|
|
||
|
|
return creds
|
||
|
|
|
||
|
|
|
||
|
|
def collect_files(skip_media: bool = False) -> list:
|
||
|
|
files = []
|
||
|
|
for directory in UPLOAD_DIRS:
|
||
|
|
root = os.path.join(APP_ROOT, directory)
|
||
|
|
if not os.path.isdir(root):
|
||
|
|
continue
|
||
|
|
for dirpath, dirnames, filenames in os.walk(root):
|
||
|
|
rel_dir = os.path.relpath(dirpath, APP_ROOT)
|
||
|
|
|
||
|
|
if skip_media and (rel_dir == MEDIA_REL or rel_dir.startswith(MEDIA_REL + os.sep)):
|
||
|
|
dirnames[:] = []
|
||
|
|
continue
|
||
|
|
|
||
|
|
dirnames[:] = [d for d in dirnames if not d.startswith('.')]
|
||
|
|
|
||
|
|
for filename in filenames:
|
||
|
|
local = os.path.join(dirpath, filename)
|
||
|
|
rel = os.path.relpath(local, APP_ROOT)
|
||
|
|
files.append((local, rel))
|
||
|
|
|
||
|
|
return files
|
||
|
|
|
||
|
|
|
||
|
|
def ensure_remote_dir(ftp: ftplib.FTP, path: str) -> None:
|
||
|
|
current = ''
|
||
|
|
for part in path.split('/'):
|
||
|
|
if part == '':
|
||
|
|
continue
|
||
|
|
current += '/' + part
|
||
|
|
try:
|
||
|
|
ftp.cwd(current)
|
||
|
|
except ftplib.all_errors:
|
||
|
|
try:
|
||
|
|
ftp.mkd(current)
|
||
|
|
ftp.cwd(current)
|
||
|
|
except ftplib.all_errors:
|
||
|
|
# Verzeichnis existiert vermutlich bereits oder ist nicht anlegbar.
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
def remote_exists(ftp: ftplib.FTP, path: str) -> bool:
|
||
|
|
try:
|
||
|
|
ftp.size(path)
|
||
|
|
return True
|
||
|
|
except ftplib.all_errors:
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
def upload_file(ftp: ftplib.FTP, local_path: str, rel: str) -> None:
|
||
|
|
remote_rel = rel.replace(os.sep, '/')
|
||
|
|
remote_full = REMOTE_BASE + '/' + remote_rel
|
||
|
|
remote_dir = '/'.join(remote_full.split('/')[:-1])
|
||
|
|
remote_name = remote_full.split('/')[-1]
|
||
|
|
|
||
|
|
ensure_remote_dir(ftp, remote_dir)
|
||
|
|
ftp.cwd(remote_dir)
|
||
|
|
|
||
|
|
with open(local_path, 'rb') as fh:
|
||
|
|
ftp.storbinary('STOR ' + remote_name, fh)
|
||
|
|
|
||
|
|
|
||
|
|
def upload_bytes(ftp: ftplib.FTP, remote_dir: str, remote_name: str, data: bytes) -> None:
|
||
|
|
ensure_remote_dir(ftp, remote_dir)
|
||
|
|
ftp.cwd(remote_dir)
|
||
|
|
ftp.storbinary('STOR ' + remote_name, io.BytesIO(data))
|
||
|
|
|
||
|
|
|
||
|
|
def env_values(creds: dict) -> dict:
|
||
|
|
host = creds.get('FTP_URL', '')
|
||
|
|
return {
|
||
|
|
'app_url': ('https://' + host) if host else 'https://motorrad-ig.de',
|
||
|
|
'db_host': creds.get('DB_HOST', '127.0.0.1'),
|
||
|
|
'db_port': creds.get('DB_PORT', '3306'),
|
||
|
|
'db_database': creds.get('DB_DATABASE', creds.get('DB_USERNAME', '')),
|
||
|
|
'db_username': creds.get('DB_USERNAME', ''),
|
||
|
|
'db_password': creds.get('DB_PASSWORD', ''),
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def build_env_content(vals: dict) -> str:
|
||
|
|
return '\n'.join([
|
||
|
|
'APP_NAME=Motorrad IG',
|
||
|
|
'APP_ENV=production',
|
||
|
|
'APP_DEBUG=false',
|
||
|
|
'APP_URL=' + vals['app_url'],
|
||
|
|
'',
|
||
|
|
'DB_HOST=' + vals['db_host'],
|
||
|
|
'DB_PORT=' + vals['db_port'],
|
||
|
|
'DB_DATABASE=' + vals['db_database'],
|
||
|
|
'DB_USERNAME=' + vals['db_username'],
|
||
|
|
'DB_PASSWORD=' + vals['db_password'],
|
||
|
|
'',
|
||
|
|
])
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> int:
|
||
|
|
parser = argparse.ArgumentParser(
|
||
|
|
description='Lädt die Web-App (public, src, views, storage, bin) per FTPS nach ' + REMOTE_BASE + ' hoch.',
|
||
|
|
epilog='Zugangsdaten werden aus ../motorradig/.credentials gelesen.',
|
||
|
|
)
|
||
|
|
parser.add_argument(
|
||
|
|
'--skip-media',
|
||
|
|
action='store_true',
|
||
|
|
help='storage/img_storage/ nicht hochladen (Benutzerbilder und PDFs).',
|
||
|
|
)
|
||
|
|
args = parser.parse_args()
|
||
|
|
|
||
|
|
creds = load_credentials(CRED_FILE)
|
||
|
|
|
||
|
|
host = creds.get('FTP_URL', '')
|
||
|
|
user = creds.get('FTP_USER', '')
|
||
|
|
password = creds.get('FTP_PASSWORD', '')
|
||
|
|
|
||
|
|
if not host or not user or not password:
|
||
|
|
print('Fehler: FTP_URL, FTP_USER und FTP_PASSWORD müssen in .credentials stehen.', file=sys.stderr)
|
||
|
|
return 1
|
||
|
|
|
||
|
|
files = collect_files(skip_media=args.skip_media)
|
||
|
|
if not files:
|
||
|
|
print('Keine Dateien zum Hochladen gefunden.', file=sys.stderr)
|
||
|
|
return 1
|
||
|
|
|
||
|
|
ftp = ftplib.FTP_TLS()
|
||
|
|
try:
|
||
|
|
ftp.connect(host, 21, timeout=30)
|
||
|
|
ftp.login(user, password)
|
||
|
|
ftp.prot_p()
|
||
|
|
ftp.set_pasv(True)
|
||
|
|
ftp.encoding = 'utf-8'
|
||
|
|
|
||
|
|
ensure_remote_dir(ftp, REMOTE_BASE)
|
||
|
|
|
||
|
|
for index, (local_path, rel) in enumerate(files, start=1):
|
||
|
|
print(f'[{index}/{len(files)}] {rel}')
|
||
|
|
upload_file(ftp, local_path, rel)
|
||
|
|
|
||
|
|
# .env prüfen: wenn nicht vorhanden, aus .credentials erzeugen und hochladen.
|
||
|
|
env_remote = REMOTE_BASE + '/.env'
|
||
|
|
if not remote_exists(ftp, env_remote):
|
||
|
|
vals = env_values(creds)
|
||
|
|
upload_bytes(ftp, REMOTE_BASE, '.env', build_env_content(vals).encode('utf-8'))
|
||
|
|
|
||
|
|
print()
|
||
|
|
print(GREEN + '.env wurde automatisch aus .credentials erzeugt und hochgeladen:' + RESET)
|
||
|
|
print(GREEN + ' ' + env_remote + RESET)
|
||
|
|
print(GREEN + ' DB_HOST=' + vals['db_host']
|
||
|
|
+ ' DB_DATABASE=' + vals['db_database']
|
||
|
|
+ ' DB_USERNAME=' + vals['db_username'] + RESET)
|
||
|
|
print(YELLOW + ' Hinweis: DB_HOST und DB_DATABASE sind Standardwerte - prüfe sie bei Bedarf.' + RESET)
|
||
|
|
print()
|
||
|
|
else:
|
||
|
|
print(GREEN + '.env ist bereits vorhanden - wird nicht überschrieben.' + RESET)
|
||
|
|
|
||
|
|
ftp.quit()
|
||
|
|
print(GREEN + f'Fertig. {len(files)} Dateien hochgeladen nach {REMOTE_BASE}/' + RESET)
|
||
|
|
return 0
|
||
|
|
except ftplib.all_errors as exc:
|
||
|
|
print(RED + 'FTPS-Fehler: ' + str(exc) + RESET, file=sys.stderr)
|
||
|
|
return 1
|
||
|
|
finally:
|
||
|
|
try:
|
||
|
|
ftp.close()
|
||
|
|
except Exception:
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
sys.exit(main())
|