#!/usr/bin/env python3 """FTP-upload of build/. Never --delete. Refuses a non-empty foreign folder.""" import os import subprocess import sys from pathlib import Path from urllib.parse import urlsplit sys.path.insert(0, str(Path(__file__).resolve().parent)) from deploy_guard import DeployGuardError, project_dir # noqa: E402 ROOT = Path(__file__).resolve().parents[1] # Files we ourselves publish; a first deploy may only land in an empty/new # folder, or a folder that already only contains a previous Meteors deploy. OURS = { 'index.html', 'game.js', 'framework.js', 'style.css', 'images', '.', '..', } def quoted(value): if any(c in value for c in '\r\n\x00'): raise ValueError('Deployment variables must not contain line breaks or NUL bytes.') return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"' def host_url(environ): for key in ['timftphost', 'timftpuser', 'timftppassword']: if not environ.get(key): raise ValueError(f'CI variable {key} is not set.') host = environ['timftphost'] if '://' not in host: host = 'ftp://' + host parsed = urlsplit(host) if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname: raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.') if parsed.username or parsed.password or parsed.query or parsed.fragment: raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.') return host def lftp_preamble(environ, host): return [ 'set cmd:fail-exit yes', 'set net:timeout 20', 'set net:max-retries 2', 'set net:reconnect-interval-base 3', 'set ssl:verify-certificate no', 'set ftp:list-options -a', 'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"', 'set sftp:auto-confirm yes', 'set xfer:use-temp-file yes', f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}', ] def run_lftp(commands, environ): subprocess.run( ['lftp', '--norc'], input='\n'.join(commands) + '\n', text=True, env={**environ, 'LFTP_PASSWORD': environ['timftppassword']}, check=True, ) def list_remote(environ, target): """Return (exists, names). exists=False means the folder is not there yet.""" host = host_url(environ) # Probe with cls; a missing folder makes `cd` fail. probe = lftp_preamble(environ, host) + [ 'set cmd:fail-exit no', f'cd {quoted(target)} && cls -1 && echo __METEORS_DIR_OK__ || echo __METEORS_DIR_MISSING__', 'bye', ] result = subprocess.run( ['lftp', '--norc'], input='\n'.join(probe) + '\n', text=True, env={**environ, 'LFTP_PASSWORD': environ['timftppassword']}, check=True, capture_output=True, ) out = (result.stdout or '') + (result.stderr or '') if '__METEORS_DIR_MISSING__' in out and '__METEORS_DIR_OK__' not in out: return False, [] names = [] for line in out.splitlines(): name = line.strip().rstrip('/') if not name or name.startswith('__METEORS_') or name.startswith('lftp'): continue # lftp may print status; keep path-like tokens if ' ' in name and not name.startswith('.'): # long listing leftover; take the last field name = name.split()[-1] names.append(posix_basename(name)) return True, names def posix_basename(name): return name.rstrip('/').split('/')[-1] def assert_safe_target(exists, names): if not exists: print('Remote meteors folder does not exist yet; it will be created.') return unexpected = [] for name in names: leaf = posix_basename(name) if leaf in OURS or leaf == '': continue unexpected.append(leaf) if unexpected: raise ValueError( 'DEPLOY GEBLOKKEERD: de map meteors op de FTP-server is niet leeg ' 'en bevat bestanden die niet bij dit project horen: ' + ', '.join(sorted(set(unexpected))[:12]) + '. Niets overschreven.' ) if names: print('Remote meteors folder already holds a previous Meteors deploy; updating.') else: print('Remote meteors folder is empty; deploying.') def deploy_commands(environ, target, webroot): host = host_url(environ) return lftp_preamble(environ, host) + [ f'mkdir -p {quoted(target)} || echo "Using existing project directory"', f'cd {quoted(target)}', # GEEN --delete. Excludes only keep CI/docs out if they were ever placed in build/. 'mirror --reverse --no-perms --no-symlinks --max-errors=1 ' '--exclude-glob ".git/" --exclude-glob ".git/**" ' '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" ' f'{quoted(str(webroot))} .', 'bye', ] def main(): environ = os.environ try: target = project_dir(environ) webroot = ROOT / 'build' if not (webroot / 'index.html').is_file() or not (webroot / 'game.js').is_file(): raise ValueError('build/ is incomplete (need index.html and game.js).') if not (webroot / 'framework.js').is_file() or not (webroot / 'images').is_dir(): raise ValueError('build/ is incomplete (need framework.js and images/).') exists, names = list_remote(environ, target) assert_safe_target(exists, names) run_lftp(deploy_commands(environ, target, webroot), environ) print('Deploy complete (no --delete).') return 0 except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error: print(str(error), file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())