|
| 1 | +"""Submit one verified release archive to the documented Marketplace update API.""" |
| 2 | +import argparse |
| 3 | +import hashlib |
| 4 | +import io |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +import re |
| 9 | +import time |
| 10 | +import urllib.error |
| 11 | +import urllib.request |
| 12 | +import uuid |
| 13 | +import xml.etree.ElementTree as ET |
| 14 | +import zipfile |
| 15 | + |
| 16 | + |
| 17 | +def validate(archive, xml_id, version, sha256): |
| 18 | + data = archive.read_bytes() |
| 19 | + assert hashlib.sha256(data).hexdigest() == sha256, 'Release archive digest differs' |
| 20 | + assert re.fullmatch(r'[A-Za-z0-9_.-]+', xml_id) |
| 21 | + assert re.fullmatch(r'\d+(?:\.\d+)+(?:[-+][A-Za-z0-9.-]+)?', version) |
| 22 | + assert re.fullmatch(r'[A-Za-z0-9_.-]+\.(?:zip|jar)', archive.name) |
| 23 | + descriptors = [] |
| 24 | + with zipfile.ZipFile(io.BytesIO(data)) as outer: |
| 25 | + for name in outer.namelist(): |
| 26 | + if not name.endswith('.jar'): |
| 27 | + continue |
| 28 | + with zipfile.ZipFile(io.BytesIO(outer.read(name))) as jar: |
| 29 | + if 'META-INF/plugin.xml' in jar.namelist(): |
| 30 | + root = ET.fromstring(jar.read('META-INF/plugin.xml')) |
| 31 | + descriptors.append((root.findtext('id'), root.findtext('version'))) |
| 32 | + assert descriptors == [(xml_id, version)], descriptors |
| 33 | + return data |
| 34 | + |
| 35 | + |
| 36 | +def submit(data, archive, xml_id, token, receipt): |
| 37 | + boundary = 'mcpp-marketplace-' + uuid.uuid4().hex |
| 38 | + prefix = ('--' + boundary + '\r\nContent-Disposition: form-data; name="xmlId"\r\n\r\n' |
| 39 | + + xml_id + '\r\n--' + boundary |
| 40 | + + '\r\nContent-Disposition: form-data; name="file"; filename="' + archive.name |
| 41 | + + '"\r\nContent-Type: application/zip\r\n\r\n').encode() |
| 42 | + body = prefix + data + ('\r\n--' + boundary + '--\r\n').encode() |
| 43 | + request = urllib.request.Request('https://plugins.jetbrains.com/api/updates/upload', body, |
| 44 | + headers={'Authorization': 'Bearer ' + token, |
| 45 | + 'Content-Type': 'multipart/form-data; boundary=' + boundary}, method='POST') |
| 46 | + class NoRedirect(urllib.request.HTTPRedirectHandler): |
| 47 | + def redirect_request(self, request, stream, code, message, headers, new_url): |
| 48 | + return None |
| 49 | + try: |
| 50 | + with urllib.request.build_opener(NoRedirect).open(request, timeout=120) as response: |
| 51 | + raw = response.read().decode(errors='replace').replace(token, '<redacted>') |
| 52 | + receipt['http'] = response.status |
| 53 | + except urllib.error.HTTPError as error: |
| 54 | + raw = error.read().decode(errors='replace').replace(token, '<redacted>') |
| 55 | + receipt.update(http=error.code, accepted=False, error=raw[:4000]) |
| 56 | + return False |
| 57 | + except (urllib.error.URLError, TimeoutError) as error: |
| 58 | + receipt.update(accepted=False, result_uncertain=True, |
| 59 | + error='Network error during the single upload; inspect Marketplace before retrying', |
| 60 | + error_type=type(error).__name__) |
| 61 | + return False |
| 62 | + try: |
| 63 | + result = json.loads(raw) |
| 64 | + except json.JSONDecodeError: |
| 65 | + result = {'text': raw[:4000]} |
| 66 | + receipt['marketplace_response'] = result |
| 67 | + receipt['accepted'] = receipt['http'] in (200, 201, 202) and not (isinstance(result, dict) and result.get('error')) |
| 68 | + return receipt['accepted'] |
| 69 | + |
| 70 | + |
| 71 | +def main(): |
| 72 | + parser = argparse.ArgumentParser(description=__doc__) |
| 73 | + parser.add_argument('--archive', required=True, type=Path) |
| 74 | + for name in ('xml-id', 'version', 'sha256'): |
| 75 | + parser.add_argument('--' + name, required=True) |
| 76 | + parser.add_argument('--output', required=True, type=Path) |
| 77 | + parser.add_argument('--verify-only', action='store_true') |
| 78 | + args = parser.parse_args() |
| 79 | + data = validate(args.archive, args.xml_id, args.version, args.sha256) |
| 80 | + receipt = dict(xml_id=args.xml_id, version=args.version, archive=args.archive.name, |
| 81 | + sha256=args.sha256, bytes=len(data), verified=True, |
| 82 | + utc=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())) |
| 83 | + if args.verify_only: |
| 84 | + receipt['upload_attempted'] = False |
| 85 | + success = True |
| 86 | + else: |
| 87 | + token = os.environ.get('JETBRAINS_TOKEN') |
| 88 | + assert token, 'JETBRAINS_TOKEN is required' |
| 89 | + receipt['upload_attempted'] = True |
| 90 | + success = submit(data, args.archive, args.xml_id, token, receipt) |
| 91 | + args.output.parent.mkdir(parents=True, exist_ok=True) |
| 92 | + args.output.write_text(json.dumps(receipt, indent=2) + '\n') |
| 93 | + print(json.dumps(receipt)) |
| 94 | + return 0 if success else 1 |
| 95 | + |
| 96 | + |
| 97 | +if __name__ == '__main__': |
| 98 | + raise SystemExit(main()) |
0 commit comments