-
Notifications
You must be signed in to change notification settings - Fork 10
/
pycli
executable file
·192 lines (151 loc) · 5.08 KB
/
pycli
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
import argparse
import functools
import os
import pathlib
import shutil
import subprocess
import sys
import types
import urllib.request
class _Registry:
def __init__(self):
self.registered = {}
def __call__(self, function=None, name=None):
if function is None and name is None:
raise TypeError("Pass a function or name.")
if function is None:
return functools.partial(self, name=name)
self.registered[function.__name__.replace("_", "-")] = function
return function
_register = _Registry()
def build_requirements_name(layer, extension):
if layer is None:
return "requirements." + extension
return layer + "-requirements." + extension
@_register
def clean(cfg):
"""Remove extraneous files."""
paths = (
[str(cfg.venv_path), ".coverage"]
+ list(pathlib.Path().glob(".coverage.*"))
+ ["dist"]
)
for path in paths:
try:
shutil.rmtree(path)
except FileNotFoundError:
pass
@_register
def init(cfg):
"""Set up a virtualenv, install requirements.txt, dev-requirements.txt, and current dir."""
subprocess.run(
["virtualenv", "--python", sys.executable, str(cfg.venv_path)], check=True
)
if not pathlib.Path(build_requirements_name(None, "txt")).exists():
raise FileNotFoundError("Run `lock` first, to create requirements.txt.")
if pathlib.Path(build_requirements_name("dev", "txt")).exists():
subprocess.run(
[
cfg.venv_path / "bin/pip",
"install",
"--requirement",
build_requirements_name("dev", "txt"),
],
check=True,
)
subprocess.run(
[cfg.venv_path / "bin/pip", "install", "--requirement", build_requirements_name(None, "txt")],
check=True,
)
subprocess.run(
[cfg.venv_path / "bin/pip", "install", "--editable", "."], check=True
)
@_register
def lock(cfg):
"""Use pip-compile to generate package hashes from setup.py and write them into requirements.txt."""
subprocess.run([cfg.venv_path / "bin/pip", "install", "pip-tools"], check=True)
combined = []
for layer in [None, 'test', 'dev']:
combined.append(layer)
subprocess.run(
[
cfg.venv_path / "bin/pip-compile",
"--generate-hashes",
"--output-file",
build_requirements_name(layer, 'txt'),
*(
build_requirements_name(prefix, 'in')
for prefix in combined
)
],
check=True,
env={
**os.environ,
"CUSTOM_COMPILE_COMMAND": "python {} lock".format(
pathlib.Path(__file__).name
),
},
)
@_register
def build(cfg):
"""Build source and binary distributions."""
subprocess.run(
[cfg.venv_path / "bin/python", "setup.py", "sdist", "bdist_wheel"], check=True
)
@_register
def upload(cfg):
"""Upload the distributions to PyPI."""
subprocess.run([cfg.venv_path / "bin/python", "-m", "pip", "install", "twine"])
dists = [str(path) for path in pathlib.Path("dist").iterdir()]
subprocess.run([cfg.venv_path / "bin/twine", "upload", *dists], check=True)
@_register
def bundle(cfg):
"""Bundle the package into a standalone unix executable."""
lock(cfg)
with open(build_requirements_name(None, "txt")) as f:
requirements = [line.split()[0] for line in f if line[0].isalpha()]
subprocess.run(
[
cfg.venv_path / "bin/pex",
".",
*requirements,
"-m",
"desert",
"-o" "desert.pex",
"--disable-cache",
]
)
def _get_default_venv_path():
"""Get the default path of the venv."""
if (pathlib.Path().resolve() / "venv").exists():
return pathlib.Path().resolve() / "venv"
venv_path = os.environ.get("VENV_PATH")
if venv_path:
return pathlib.Path(venv_path)
workon_home = os.environ.get("WORKON_HOME")
if workon_home is not None:
project_name = pathlib.Path(os.getcwd()).name
return pathlib.Path(workon_home) / project_name
return pathlib.Path().resolve() / "venv"
def cli():
parser = argparse.ArgumentParser()
parser.add_argument(
"--venv",
default=_get_default_venv_path(),
type=pathlib.Path,
help="Path of the venv directory. Defaults, in order: venv (if exists already), $VENV_PATH, $WORKON_HOME/[current directory name], venv",
)
subparsers = parser.add_subparsers(dest="command_name")
for name, function in _register.registered.items():
subparsers.add_parser(name, help=function.__doc__)
args = parser.parse_args()
if args.command_name is None:
parser.print_help()
sys.exit(2)
function = _register.registered[args.command_name]
cfg = types.SimpleNamespace()
cfg.venv_path = args.venv
function(cfg)
if __name__ == "__main__":
cli()