BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / ci / deploy.py

deploy.py

deploy.py 3.9 KiB Download Raw
1#!/usr/bin/env python3
2"""Deploy only web/, preserving server-owned data. Passwords never enter argv."""
3import os
4from pathlib import Path
5import subprocess
6import sys
7from urllib.parse import urlsplit
8
9sys.path.insert(0, str(Path(__file__).resolve().parent))
10from deploy_guard import project_dir # noqa: E402
11
12ROOT = Path(__file__).resolve().parents[1]
13
14def quoted(value):
15 if any(c in value for c in '\r\n\x00'):
16 raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')
17 return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
18
19def deployment_commands(environ, webroot):
20 # Hard guard first: never mirror --delete into the site root.
21 target = project_dir(environ)
22 for key in ['timftphost', 'timftpuser', 'timftppassword']:
23 if not environ.get(key):
24 raise ValueError(f'CI variable {key} is not set.')
25 host = environ['timftphost']
26 if '://' not in host:
27 host = 'ftp://' + host
28 parsed = urlsplit(host)
29 if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:
30 raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')
31 if parsed.username or parsed.password or parsed.query or parsed.fragment:
32 raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')
33 commands = [
34 'set cmd:fail-exit yes',
35 'set net:timeout 20',
36 'set net:max-retries 2',
37 'set net:reconnect-interval-base 3',
38 # This hosting account uses a mismatched FTP certificate; retain the owner's deployment policy.
39 'set ssl:verify-certificate no',
40 'set ftp:list-options -a',
41 # New SFTP hosts are remembered within this runner; changed host keys fail.
42 'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
43 f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
44 # First deploy: the project folder may not exist yet on the server.
45 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
46 f'cd {quoted(target)}',
47 'mkdir -p data || echo "Using existing data directory"',
48 f'put {quoted(str(webroot / "data/.htaccess"))} -o data/.htaccess',
49 # No --delete-excluded: these paths belong to the running server.
50 'mirror --reverse --delete --no-perms --no-symlinks --max-errors=1 '
51 '--exclude-glob "data/" --exclude-glob "data/**" '
52 '--exclude-glob "tests/" --exclude-glob "tests/**" '
53 '--exclude-glob "README.md" --exclude-glob "router.php" '
54 f'{quoted(str(webroot))} .',
55 'bye',
56 ]
57 return '\n'.join(commands) + '\n'
58
59def write_asset_version(webroot, environ=None):
60 """Stamp the deploy commit into web/asset-version.txt for cache-busting."""
61 environ = os.environ if environ is None else environ
62 sha = (environ.get('CI_COMMIT_SHA') or '').strip()
63 if not sha:
64 try:
65 sha = subprocess.check_output(
66 ['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True, stderr=subprocess.DEVNULL
67 ).strip()
68 except (subprocess.CalledProcessError, FileNotFoundError):
69 sha = ''
70 if not sha or len(sha) < 7:
71 raise ValueError('Unable to determine commit SHA for asset-version.txt (set CI_COMMIT_SHA).')
72 (webroot / 'asset-version.txt').write_text(sha + '\n', encoding='utf-8')
73 print(f'Wrote asset-version.txt = {sha}')
74
75def main():
76 try:
77 webroot = ROOT / 'web'
78 write_asset_version(webroot, os.environ)
79 commands = deployment_commands(os.environ, webroot)
80 subprocess.run(['lftp', '--norc'], input=commands, text=True,
81 env={**os.environ, 'LFTP_PASSWORD':os.environ['timftppassword']}, check=True)
82 except (ValueError, subprocess.CalledProcessError) as error:
83 print(str(error), file=sys.stderr)
84 return 1
85 return 0
86
87if __name__ == '__main__':
88 sys.exit(main())