summaryrefslogtreecommitdiff
path: root/scripts/internal/download_wheels_github.py
blob: 8a16d3371a20e6679ef283b59739ba23241150be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/env python3

# Copyright (c) 2009 Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Script which downloads wheel files hosted on GitHub:
https://github.com/giampaolo/psutil/actions
It needs an access token string generated from personal GitHub profile:
https://github.com/settings/tokens
The token must be created with at least "public_repo" scope/rights.
If you lose it, just generate a new token.
REST API doc:
https://developer.github.com/v3/actions/artifacts/
"""

import argparse
import collections
import json
import os
import requests
import zipfile

from psutil._common import bytes2human
from psutil._common import print_color
from psutil.tests import safe_rmpath


USER = ""
PROJECT = ""
TOKEN = ""
OUTFILE = "wheels-github.zip"


# --- GitHub API


def get_artifacts():
    base_url = "https://api.github.com/repos/%s/%s" % (USER, PROJECT)
    url = base_url + "/actions/artifacts"
    res = requests.get(url=url, headers={"Authorization": "token %s" % TOKEN})
    res.raise_for_status()
    data = json.loads(res.content)
    return data


def download_zip(url):
    print("downloading: " + url)
    res = requests.get(url=url, headers={"Authorization": "token %s" % TOKEN})
    res.raise_for_status()
    totbytes = 0
    with open(OUTFILE, 'wb') as f:
        for chunk in res.iter_content(chunk_size=16384):
            f.write(chunk)
            totbytes += len(chunk)
    print("got %s, size %s)" % (OUTFILE, bytes2human(totbytes)))


# --- extract


def extract():
    with zipfile.ZipFile(OUTFILE, 'r') as zf:
        zf.extractall('dist')


def print_wheels():
    def is64bit(name):
        return name.endswith(('x86_64.whl', 'amd64.whl'))

    groups = collections.defaultdict(list)
    for name in os.listdir('dist'):
        plat = name.split('-')[-1]
        pyimpl = name.split('-')[3]
        ispypy = 'pypy' in pyimpl
        if 'linux' in plat:
            if ispypy:
                groups['pypy_on_linux'].append(name)
            else:
                groups['linux'].append(name)
        elif 'win' in plat:
            if ispypy:
                groups['pypy_on_windows'].append(name)
            else:
                groups['windows'].append(name)
        elif 'macosx' in plat:
            if ispypy:
                groups['pypy_on_macos'].append(name)
            else:
                groups['macos'].append(name)
        else:
            assert 0, name

    totsize = 0
    templ = "%-54s %7s %7s %7s"
    for platf, names in groups.items():
        ppn = "%s (total = %s)" % (platf.replace('_', ' '), len(names))
        s = templ % (ppn, "size", "arch", "pyver")
        print_color('\n' + s, color=None, bold=True)
        for name in sorted(names):
            path = os.path.join('dist', name)
            size = os.path.getsize(path)
            totsize += size
            arch = '64' if is64bit(name) else '32'
            pyver = 'pypy' if name.split('-')[3].startswith('pypy') else 'py'
            pyver += name.split('-')[2][2:]
            s = templ % (name, bytes2human(size), arch, pyver)
            if 'pypy' in pyver:
                print_color(s, color='violet')
            else:
                print_color(s, color='brown')


def run():
    data = get_artifacts()
    download_zip(data['artifacts'][0]['archive_download_url'])
    os.makedirs('dist', exist_ok=True)
    extract()
    print_wheels()


def main():
    global USER, PROJECT, TOKEN
    parser = argparse.ArgumentParser(description='GitHub wheels downloader')
    parser.add_argument('--user', required=True)
    parser.add_argument('--project', required=True)
    parser.add_argument('--tokenfile', required=True)
    args = parser.parse_args()
    USER = args.user
    PROJECT = args.project
    with open(os.path.expanduser(args.tokenfile)) as f:
        TOKEN = f.read().strip()
    try:
        run()
    finally:
        safe_rmpath(OUTFILE)


if __name__ == '__main__':
    main()