summarylogtreecommitdiffstats
path: root/install-wheel-scripts.py
blob: 0842e4cb991fb0195357afc38935565e6b56bdb9 (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
#!/usr/bin/env python3

import argparse
from pathlib import Path
from configparser import ConfigParser
from zipfile import ZipFile


parser = argparse.ArgumentParser(description='Install wheel scripts.')
parser.add_argument('wheel', type=Path, help='Wheel file')
parser.add_argument('--prefix', type=Path, default=Path('/usr/local/'), help='Installation prefix (/usr/, ~/.local, …)')


def get_console_scripts(whl):
	with ZipFile(whl) as archive:
		n = next(iter(n for n in archive.namelist() if n.endswith('.dist-info/entry_points.txt')), None)
		if n is None:
			return {}
		ini = archive.read(n).decode('utf-8')
	parser = ConfigParser()
	parser.optionxform = str  # case sensitive
	parser.read_string(ini)
	return dict(parser['console_scripts']) if 'console_scripts' in parser else {}


def main():
	args = parser.parse_args()
	
	scripts = get_console_scripts(args.wheel)
	for name, defn in scripts.items():
		defn, *_ = defn.split(';')  # extra condition
		mod, fun = defn.split(':')
		if mod.endswith('.__main__'):
			mod = mod[:-len('.__main__')]
			code = f'''\
#!/bin/sh
exec /usr/bin/python3 -m {mod} "$@"
'''
		else:
			code = f'''\
#!/usr/bin/python3
from {mod} import {fun}
{fun}()
'''
		bin_path = args.prefix / 'bin' / name
		bin_path.parent.mkdir(parents=True, exist_ok=True)
		bin_path.write_text(code)
		bin_path.chmod(0o755)


if __name__ == '__main__':
	main()