xref: /openbsd/gnu/llvm/llvm/utils/gn/get.py (revision d415bd75)
1#!/usr/bin/env python3
2"""Downloads a prebuilt gn binary to a place where gn.py can find it."""
3
4import io
5import os
6import sys
7import urllib.request
8import zipfile
9
10
11def download_and_unpack(url, output_dir, gn):
12    """Download an archive from url and extract gn from it into output_dir."""
13    print('downloading %s ...' % url, end='')
14    sys.stdout.flush()
15    data = urllib.request.urlopen(url).read()
16    print(' done')
17    zipfile.ZipFile(io.BytesIO(data)).extract(gn, path=output_dir)
18
19
20def set_executable_bit(path):
21    mode = os.stat(path).st_mode
22    mode |= (mode & 0o444) >> 2 # Copy R bits to X.
23    os.chmod(path, mode) # No-op on Windows.
24
25
26def get_platform():
27    import platform
28    if sys.platform == 'darwin':
29        return 'mac-amd64' if platform.machine() != 'arm64' else 'mac-arm64'
30    if platform.machine() not in ('AMD64', 'x86_64'):
31        return None
32    if sys.platform.startswith('linux'):
33        return 'linux-amd64'
34    if sys.platform == 'win32':
35        return 'windows-amd64'
36
37
38def main():
39    platform = get_platform()
40    if not platform:
41        print('no prebuilt binary for', sys.platform)
42        print('build it yourself with:')
43        print('  rm -rf /tmp/gn &&')
44        print('  pushd /tmp && git clone https://gn.googlesource.com/gn &&')
45        print('  cd gn && build/gen.py && ninja -C out gn && popd &&')
46        print('  cp /tmp/gn/out/gn somewhere/on/PATH')
47        return 1
48    dirname = os.path.join(os.path.dirname(__file__), 'bin', platform)
49    if not os.path.exists(dirname):
50        os.makedirs(dirname)
51
52    url = 'https://chrome-infra-packages.appspot.com/dl/gn/gn/%s/+/latest'
53    gn = 'gn' + ('.exe' if sys.platform == 'win32' else '')
54    if platform == 'mac-arm64': # For https://openradar.appspot.com/FB8914243
55        try: os.remove(os.path.join(dirname, gn))
56        except OSError: pass
57    download_and_unpack(url % platform, dirname, gn)
58    set_executable_bit(os.path.join(dirname, gn))
59
60
61if __name__ == '__main__':
62    sys.exit(main())
63