Files
cutdex/tool/windows/windows_updates.py
T

170 lines
7.8 KiB
Python

"""Package audited Windows releases with Velopack, or serve a loopback test feed."""
import argparse
from functools import partial
import hashlib
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import re
import subprocess
import sys
from urllib.parse import urljoin, urlparse
from urllib.request import url2pathname
from check_windows_release import audit
from update_versions import numeric_version, update_version
ROOT = Path(__file__).resolve().parents[2]
def resolved_deskup():
config = ROOT / '.dart_tool/package_config.json'
if not config.is_file():
raise ValueError('Run flutter pub get before using Windows update tools')
packages = json.loads(config.read_text(encoding='utf-8'))['packages']
package = next(item for item in packages if item['name'] == 'deskup')
uri = urlparse(urljoin(config.as_uri(), package['rootUri']))
if uri.scheme != 'file' or uri.netloc:
raise ValueError('Expected a local resolved deskup package')
return Path(url2pathname(uri.path))
DESKUP_ROOT = resolved_deskup()
DESKUP_VERSION = re.search(r'^version: ([^\s]+)',
(DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'),
re.MULTILINE).group(1)
SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)',
(DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1)
def vpk_command(path):
path = Path(path).resolve()
if path.suffix.lower() == '.dll':
# Useful with a locally extracted official vpk tool package.
return ['dotnet', str(path), '--legacyConsole', '--skip-updates']
return [str(path), '--legacyConsole', '--skip-updates']
def check_tool(command):
result = subprocess.run(command + ['--help'], capture_output=True, text=True,
encoding='utf-8', errors='replace', check=True, timeout=30)
if not re.search(rf'(?<![\d.]){re.escape(SDK_VERSION)}(?![\d.])', result.stdout + result.stderr):
raise ValueError(f'Use vpk {SDK_VERSION} to match the native SDK')
def pack_release(command, *, app, output, package_id, version, title):
numeric_version(version)
subprocess.run(command + ['pack', '--packId', package_id, '--packVersion', version,
'--packDir', str(app), '--mainExe', 'cutdex.exe',
'--packTitle', title, '--runtime', 'win-x64',
'--channel', 'win-x64', '--outputDir', str(output),
'--delta', 'none'], check=True)
def file_version(app):
import pefile
with pefile.PE(str(app / 'cutdex.exe')) as pe:
for group in pe.FileInfo:
for block in group:
if block.Key == b'StringFileInfo':
for table in block.StringTable:
value = table.entries.get(b'ProductVersion', b'').decode('utf-8')
match = re.fullmatch(r'(\d+\.\d+\.\d+)\+(\d+)', value)
if match:
return update_version(match[1], match[2])
raise ValueError('Missing Flutter display version and build number in PE resources')
def validate_previous(output, package_id, version):
candidate = numeric_version(version)
for feed in output.glob('releases.*.json'):
for asset in json.loads(feed.read_text(encoding='utf-8-sig')).get('Assets', []):
if asset.get('PackageId') != package_id:
raise ValueError('Do not mix production and development packages in one release directory')
if numeric_version(asset['Version']) >= candidate:
raise ValueError('Update version must be greater than every previously published version')
def verify_manifest(app):
app = app.resolve()
manifest = json.loads((app / 'checksums.json').read_text(encoding='utf-8-sig'))
actual_files = {file.relative_to(app).as_posix() for file in app.rglob('*')
if file.is_file() and file.name != 'checksums.json'}
# The processing subtree has its own checksum manifest, which is included
# as a file in the outer app manifest.
actual_files.update(file.relative_to(app).as_posix() for file in app.rglob('checksums.json')
if file != app / 'checksums.json')
if set(manifest) != actual_files:
raise ValueError('Release files differ from the audited staging manifest')
for name, expected in manifest.items():
candidate = app / name
file = candidate.resolve()
if not file.is_relative_to(app) or candidate.is_symlink():
raise ValueError(f'Invalid manifest path: {name}')
with file.open('rb') as stream:
if hashlib.file_digest(stream, 'sha256').hexdigest().lower() != expected.lower():
raise ValueError(f'Release checksum mismatch: {name}')
def package_app(app, output, vpk, *, development=False, require_processing=True):
app, output = Path(app).resolve(), Path(output).resolve()
if output == app or output.is_relative_to(app) or app.is_relative_to(output):
raise ValueError('Release output must be outside the staged app')
audit(app, require_processing=require_processing)
verify_manifest(app)
sdk_dll = app / 'velopack_libc.dll'
if not sdk_dll.is_file():
raise ValueError('Rebuild the app with the Velopack integration before packaging')
command = vpk_command(vpk)
check_tool(command)
version = file_version(app)
package_id = 'Cutdex.Dev' if development else 'Cutdex'
# deskup compiles the identity into the plugin, rather than the runner.
identity = package_id.encode('ascii') + b'\0'
if identity not in (app / 'deskup_plugin.dll').read_bytes():
raise ValueError('Package identity does not match the Flutter build flavor')
validate_previous(output, package_id, version)
output.mkdir(parents=True, exist_ok=True)
pack_release(command, app=app, output=output, package_id=package_id, version=version,
title='Cutdex Dev' if development else 'Cutdex')
return {'version': version, 'packageId': package_id, 'output': str(output)}
def serve(directory, port):
directory = directory.resolve()
if not directory.is_dir():
raise ValueError('Provide an existing Velopack release directory')
with ThreadingHTTPServer(('127.0.0.1', port),
partial(SimpleHTTPRequestHandler, directory=str(directory))) as server:
print(f'Test update source: http://127.0.0.1:{server.server_port}', flush=True)
server.serve_forever()
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
pack = commands.add_parser('pack', help='Package a complete audited release; never uploads')
pack.add_argument('--app', type=Path, required=True)
pack.add_argument('--output', type=Path, required=True)
pack.add_argument('--vpk', type=Path, required=True)
pack.add_argument('--development', action='store_true')
server = commands.add_parser('serve', help='Serve a test feed on 127.0.0.1 only')
server.add_argument('--directory', type=Path, required=True)
server.add_argument('--port', type=int, default=8765)
args = parser.parse_args()
try:
if args.command == 'pack':
print(json.dumps(package_app(args.app, args.output, args.vpk,
development=args.development)))
else:
serve(args.directory, args.port)
except KeyboardInterrupt:
return
except (ValueError, OSError) as error:
print(str(error), file=sys.stderr)
raise SystemExit(1) from error
except subprocess.CalledProcessError as error:
raise SystemExit(error.returncode) from error
if __name__ == '__main__':
main()