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