venvpool 27__tar.gz → 28__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {venvpool-27 → venvpool-28}/PKG-INFO +1 -17
- {venvpool-27 → venvpool-28}/README.md +0 -16
- {venvpool-27 → venvpool-28}/setup.py +1 -1
- venvpool-28/venvpool/__init__.py +515 -0
- venvpool-28/venvpool/execute.py +37 -0
- venvpool-28/venvpool/launch.py +39 -0
- venvpool-28/venvpool/motivate.py +164 -0
- {venvpool-27 → venvpool-28}/venvpool/tempvenv.py +4 -4
- {venvpool-27 → venvpool-28}/venvpool.egg-info/PKG-INFO +1 -17
- {venvpool-27 → venvpool-28}/venvpool.egg-info/SOURCES.txt +2 -0
- venvpool-27/venvpool/__init__.py +0 -927
- venvpool-27/venvpool/motivate.py +0 -5
- {venvpool-27 → venvpool-28}/setup.cfg +0 -0
- {venvpool-27 → venvpool-28}/venvpool/util.py +0 -0
- {venvpool-27 → venvpool-28}/venvpool.egg-info/dependency_links.txt +0 -0
- {venvpool-27 → venvpool-28}/venvpool.egg-info/entry_points.txt +0 -0
- {venvpool-27 → venvpool-28}/venvpool.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.2
|
|
2
2
|
Name: venvpool
|
|
3
|
-
Version:
|
|
3
|
+
Version: 28
|
|
4
4
|
Summary: Run your Python scripts using an automated pool of virtual environments to satisfy their requirements
|
|
5
5
|
Home-page: https://pypi.org/project/venvpool/
|
|
6
6
|
Author: foyono
|
|
@@ -29,22 +29,6 @@ Create and maintain wrapper scripts in ~/.local/bin for all runnable modules in
|
|
|
29
29
|
|
|
30
30
|
### venvpool
|
|
31
31
|
|
|
32
|
-
<a id="venvpool.dotpy"></a>
|
|
33
|
-
|
|
34
|
-
###### dotpy
|
|
35
|
-
|
|
36
|
-
Python source file extension including dot.
|
|
37
|
-
|
|
38
|
-
<a id="venvpool.initlogging"></a>
|
|
39
|
-
|
|
40
|
-
###### initlogging
|
|
41
|
-
|
|
42
|
-
```python
|
|
43
|
-
def initlogging()
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
Initialise the logging module to send debug (and higher levels) to stderr.
|
|
47
|
-
|
|
48
32
|
<a id="venvpool.util"></a>
|
|
49
33
|
|
|
50
34
|
### venvpool.util
|
|
@@ -14,22 +14,6 @@ Create and maintain wrapper scripts in ~/.local/bin for all runnable modules in
|
|
|
14
14
|
|
|
15
15
|
### venvpool
|
|
16
16
|
|
|
17
|
-
<a id="venvpool.dotpy"></a>
|
|
18
|
-
|
|
19
|
-
###### dotpy
|
|
20
|
-
|
|
21
|
-
Python source file extension including dot.
|
|
22
|
-
|
|
23
|
-
<a id="venvpool.initlogging"></a>
|
|
24
|
-
|
|
25
|
-
###### initlogging
|
|
26
|
-
|
|
27
|
-
```python
|
|
28
|
-
def initlogging()
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
Initialise the logging module to send debug (and higher levels) to stderr.
|
|
32
|
-
|
|
33
17
|
<a id="venvpool.util"></a>
|
|
34
18
|
|
|
35
19
|
### venvpool.util
|
|
@@ -49,7 +49,7 @@ class SourceInfo:
|
|
|
49
49
|
sourceinfo = SourceInfo('.')
|
|
50
50
|
setup(
|
|
51
51
|
name = 'venvpool',
|
|
52
|
-
version = '
|
|
52
|
+
version = '28',
|
|
53
53
|
description = 'Run your Python scripts using an automated pool of virtual environments to satisfy their requirements',
|
|
54
54
|
url = 'https://pypi.org/project/venvpool/',
|
|
55
55
|
author = 'foyono',
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
from collections import OrderedDict
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
from random import shuffle # XXX: Expensive?
|
|
4
|
+
from stat import S_IXUSR, S_IXGRP, S_IXOTH
|
|
5
|
+
from tempfile import mkdtemp, mkstemp, TemporaryDirectory
|
|
6
|
+
import errno, logging, operator, os, re, shutil, sys # XXX: Still expensive?
|
|
7
|
+
|
|
8
|
+
class subprocess:
|
|
9
|
+
|
|
10
|
+
def __getattr__(self, name):
|
|
11
|
+
import subprocess # Up to a hundredth.
|
|
12
|
+
return getattr(subprocess, name)
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger(__name__)
|
|
15
|
+
chainrelpath = os.path.join('venvpool', 'chain.py')
|
|
16
|
+
dotpy = '.py'
|
|
17
|
+
executablebits = S_IXUSR | S_IXGRP | S_IXOTH
|
|
18
|
+
oserrors = {code: type(name, (OSError,), {}) for code, name in errno.errorcode.items()}
|
|
19
|
+
pooldir = os.path.join(os.environ.get('XDG_CACHE_HOME') or os.path.join(os.path.expanduser('~'), '.cache'), 'venvpool')
|
|
20
|
+
scriptregex, = (r"^if\s+(?:__name__\s*==\s*{main}|{main}\s*==\s*__name__)\s*:\s*$".format(**locals()) for main in ['''(?:'__main__'|"__main__")'''])
|
|
21
|
+
try:
|
|
22
|
+
set_inheritable = os.set_inheritable
|
|
23
|
+
except AttributeError:
|
|
24
|
+
from fcntl import fcntl, FD_CLOEXEC, F_GETFD, F_SETFD
|
|
25
|
+
def set_inheritable(h, inherit):
|
|
26
|
+
assert inherit
|
|
27
|
+
fcntl(h, F_SETFD, fcntl(h, F_GETFD) & ~FD_CLOEXEC)
|
|
28
|
+
subprocess = subprocess()
|
|
29
|
+
userbin = os.path.join(os.path.expanduser('~'), '.local', 'bin')
|
|
30
|
+
|
|
31
|
+
def _osop(f, *args, **kwargs):
|
|
32
|
+
try:
|
|
33
|
+
return f(*args, **kwargs)
|
|
34
|
+
except OSError as e:
|
|
35
|
+
raise oserrors[e.errno](*e.args)
|
|
36
|
+
|
|
37
|
+
@contextmanager
|
|
38
|
+
def _onerror(f):
|
|
39
|
+
try:
|
|
40
|
+
yield
|
|
41
|
+
except:
|
|
42
|
+
f()
|
|
43
|
+
raise
|
|
44
|
+
|
|
45
|
+
class Pip:
|
|
46
|
+
|
|
47
|
+
envpatch = dict(PYTHON_KEYRING_BACKEND = 'keyring.backends.null.Keyring')
|
|
48
|
+
|
|
49
|
+
def __init__(self, pippath):
|
|
50
|
+
self.pippath = pippath
|
|
51
|
+
|
|
52
|
+
def pipinstall(self, command):
|
|
53
|
+
subprocess.check_call([self.pippath, 'install'] + command, env = dict(os.environ, **self.envpatch), stdout = sys.stderr)
|
|
54
|
+
|
|
55
|
+
def listorempty(d, xform = lambda p: p, accept = lambda n: n):
|
|
56
|
+
try:
|
|
57
|
+
names = _osop(os.listdir, d)
|
|
58
|
+
except oserrors[errno.ENOENT]:
|
|
59
|
+
return []
|
|
60
|
+
return [xform(os.path.join(d, n)) for n in sorted(names) if accept(n)]
|
|
61
|
+
|
|
62
|
+
class LockStateException(Exception): pass
|
|
63
|
+
|
|
64
|
+
class ReadLock:
|
|
65
|
+
|
|
66
|
+
def __init__(self, handle):
|
|
67
|
+
self.handle = handle
|
|
68
|
+
|
|
69
|
+
def unlock(self):
|
|
70
|
+
try:
|
|
71
|
+
_osop(os.close, self.handle)
|
|
72
|
+
except oserrors[errno.EBADF]:
|
|
73
|
+
raise LockStateException
|
|
74
|
+
|
|
75
|
+
def _idempotentunlink(path):
|
|
76
|
+
try:
|
|
77
|
+
_osop(os.remove, path)
|
|
78
|
+
return True
|
|
79
|
+
except oserrors[errno.ENOENT]:
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
def _chunkify(n, v):
|
|
83
|
+
i = iter(v)
|
|
84
|
+
while True:
|
|
85
|
+
chunk = []
|
|
86
|
+
for _ in range(n):
|
|
87
|
+
try:
|
|
88
|
+
x = next(i)
|
|
89
|
+
except StopIteration:
|
|
90
|
+
if chunk:
|
|
91
|
+
yield chunk
|
|
92
|
+
return
|
|
93
|
+
chunk.append(x)
|
|
94
|
+
yield chunk
|
|
95
|
+
|
|
96
|
+
if '/' == os.sep:
|
|
97
|
+
def _swept(readlocks):
|
|
98
|
+
for chunk in _chunkify(1000, readlocks):
|
|
99
|
+
# Check stderr instead of returncode for errors:
|
|
100
|
+
stdout, stderr = subprocess.Popen(['lsof', '-t'] + chunk, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
|
|
101
|
+
if not stderr and not stdout:
|
|
102
|
+
for readlock in chunk:
|
|
103
|
+
if _idempotentunlink(readlock):
|
|
104
|
+
yield readlock
|
|
105
|
+
else:
|
|
106
|
+
def _swept(readlocks): # TODO: Untested!
|
|
107
|
+
for readlock in readlocks:
|
|
108
|
+
try:
|
|
109
|
+
if _idempotentunlink(readlock):
|
|
110
|
+
yield readlock
|
|
111
|
+
except oserrors[errno.EACCES]:
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
def _compress(paths, splitchar = os.sep):
|
|
115
|
+
if not paths:
|
|
116
|
+
yield '-' # Avoid empty word in command line.
|
|
117
|
+
return
|
|
118
|
+
firstdiff = -1
|
|
119
|
+
for firstdiff, chars in enumerate(zip(*paths)):
|
|
120
|
+
if 1 != len(set(chars)):
|
|
121
|
+
break
|
|
122
|
+
else:
|
|
123
|
+
firstdiff += 1
|
|
124
|
+
while firstdiff and paths[0][firstdiff - 1] != splitchar:
|
|
125
|
+
firstdiff -= 1
|
|
126
|
+
yield paths[0][:firstdiff]
|
|
127
|
+
for p in paths:
|
|
128
|
+
yield p[firstdiff:]
|
|
129
|
+
|
|
130
|
+
class SharedDir:
|
|
131
|
+
|
|
132
|
+
readlocksname = 'readlocks'
|
|
133
|
+
|
|
134
|
+
def __init__(self, dirpath):
|
|
135
|
+
self.readlocks = os.path.join(dirpath, self.readlocksname)
|
|
136
|
+
|
|
137
|
+
def _sweep(self):
|
|
138
|
+
paths = list(_compress(list(_swept(listorempty(self.readlocks)))))
|
|
139
|
+
n = len(paths)
|
|
140
|
+
if 2 == n:
|
|
141
|
+
log.debug("Swept: %s%s", *paths)
|
|
142
|
+
elif 2 < n:
|
|
143
|
+
log.debug("Swept: %s{%s}", paths[0], ','.join(paths[1:]))
|
|
144
|
+
|
|
145
|
+
def trywritelock(self):
|
|
146
|
+
self._sweep()
|
|
147
|
+
try:
|
|
148
|
+
_osop(os.rmdir, self.readlocks)
|
|
149
|
+
return True
|
|
150
|
+
except (oserrors[errno.ENOENT], oserrors[errno.ENOTEMPTY]):
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
def createortrywritelock(self):
|
|
154
|
+
try:
|
|
155
|
+
_osop(os.mkdir, os.path.dirname(self.readlocks))
|
|
156
|
+
return True
|
|
157
|
+
except oserrors[errno.EEXIST]:
|
|
158
|
+
return self.trywritelock()
|
|
159
|
+
|
|
160
|
+
def writeunlock(self):
|
|
161
|
+
try:
|
|
162
|
+
_osop(os.mkdir, self.readlocks) # XXX: Do nothing if parent has been deleted?
|
|
163
|
+
except oserrors[errno.EEXIST]:
|
|
164
|
+
raise LockStateException
|
|
165
|
+
|
|
166
|
+
def tryreadlock(self):
|
|
167
|
+
try:
|
|
168
|
+
h = _osop(mkstemp, dir = self.readlocks, prefix = 'lock')[0]
|
|
169
|
+
set_inheritable(h, True)
|
|
170
|
+
return ReadLock(h)
|
|
171
|
+
except oserrors[errno.ENOENT]:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
def safe_name(name):
|
|
175
|
+
return re.sub('[^A-Za-z0-9.]+', '-', name)
|
|
176
|
+
|
|
177
|
+
def to_filename(name):
|
|
178
|
+
return name.replace('-', '_')
|
|
179
|
+
|
|
180
|
+
class CompactVenv:
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def site_packages(self):
|
|
184
|
+
libpath = os.path.join(self.venvpath, 'lib')
|
|
185
|
+
pyname, = (n for n in os.listdir(libpath) if n.startswith('python'))
|
|
186
|
+
return os.path.join(libpath, pyname, 'site-packages')
|
|
187
|
+
|
|
188
|
+
def __init__(self, venvpath):
|
|
189
|
+
self.venvpath = venvpath
|
|
190
|
+
|
|
191
|
+
def create(self, uv):
|
|
192
|
+
subprocess.check_call([uv, 'venv', '--quiet', '--relocatable', self.venvpath])
|
|
193
|
+
chainpath = os.path.join(self.site_packages, chainrelpath)
|
|
194
|
+
os.mkdir(os.path.dirname(chainpath))
|
|
195
|
+
with open(chainpath, 'w') as f:
|
|
196
|
+
f.write('''import os, sys
|
|
197
|
+
v = [os.path.join(os.path.dirname(sys.executable), sys.argv[1])] + sys.argv[2:]
|
|
198
|
+
os.execv(v[0], v)
|
|
199
|
+
''')
|
|
200
|
+
|
|
201
|
+
def delete(self, label = 'transient'):
|
|
202
|
+
log.debug("Delete %s venv: %s", label, self.venvpath)
|
|
203
|
+
shutil.rmtree(self.venvpath)
|
|
204
|
+
|
|
205
|
+
def programpath(self, name):
|
|
206
|
+
return os.path.join(self.venvpath, 'bin', name)
|
|
207
|
+
|
|
208
|
+
def install(self, args, uv):
|
|
209
|
+
log.debug("Install: %s", ' '.join(args))
|
|
210
|
+
if args:
|
|
211
|
+
subprocess.check_call([uv, 'pip', 'install', '--quiet', '--python', self.venvpath, *args])
|
|
212
|
+
|
|
213
|
+
def compatible(self, installdeps):
|
|
214
|
+
for r in installdeps.pypireqs:
|
|
215
|
+
version = self._reqversionornone(r.namepart)
|
|
216
|
+
if version is None or not r.acceptversion(version):
|
|
217
|
+
return
|
|
218
|
+
log.debug("Found compatible venv: %s", self.venvpath)
|
|
219
|
+
return True
|
|
220
|
+
|
|
221
|
+
def _reqversionornone(self, name):
|
|
222
|
+
patterns = [re.compile(format % nameregex) for nameregex in [re.escape(to_filename(safe_name(name)).lower())] for format in [
|
|
223
|
+
"^%s-(.+)[.]dist-info$",
|
|
224
|
+
"^%s-([^-]+).*[.]egg-info$"]]
|
|
225
|
+
for lowername in (n.lower() for n in os.listdir(self.site_packages)):
|
|
226
|
+
for p in patterns:
|
|
227
|
+
m = p.search(lowername)
|
|
228
|
+
if m is not None:
|
|
229
|
+
return m.group(1)
|
|
230
|
+
|
|
231
|
+
def run(self, mode, localreqs, task, scriptargs, **kwargs):
|
|
232
|
+
try:
|
|
233
|
+
patch = task.patch
|
|
234
|
+
module = task.module
|
|
235
|
+
except AttributeError:
|
|
236
|
+
patch = '#'
|
|
237
|
+
module = task
|
|
238
|
+
argv = [os.path.join(self.venvpath, 'bin', 'python'), os.path.join(os.path.dirname(__file__), 'execute.py'), os.pathsep.join(_compress(localreqs)), patch, module] + scriptargs
|
|
239
|
+
if 'call' == mode:
|
|
240
|
+
return subprocess.call(argv, **kwargs)
|
|
241
|
+
if 'check_call' == mode:
|
|
242
|
+
return subprocess.check_call(argv, **kwargs)
|
|
243
|
+
if 'check_output' == mode:
|
|
244
|
+
return subprocess.check_output(argv, **kwargs)
|
|
245
|
+
if 'exec' == mode:
|
|
246
|
+
os.execv(argv[0], argv, **kwargs)
|
|
247
|
+
raise ValueError(mode)
|
|
248
|
+
|
|
249
|
+
class CompactPool:
|
|
250
|
+
|
|
251
|
+
prefix = 'venv'
|
|
252
|
+
|
|
253
|
+
def __init__(self):
|
|
254
|
+
self.readonlyortransient = {
|
|
255
|
+
False: self.readonly,
|
|
256
|
+
True: self._transient,
|
|
257
|
+
}
|
|
258
|
+
self.readonlyorreadwrite = {
|
|
259
|
+
False: self.readonly,
|
|
260
|
+
True: self.readwrite,
|
|
261
|
+
}
|
|
262
|
+
self.directory = d = os.path.join(pooldir, 'compact')
|
|
263
|
+
try:
|
|
264
|
+
_osop(os.makedirs, d)
|
|
265
|
+
except oserrors[errno.EEXIST]:
|
|
266
|
+
pass
|
|
267
|
+
self.lockpath = os.path.join(d, 'lock')
|
|
268
|
+
|
|
269
|
+
@contextmanager
|
|
270
|
+
def _lock(self):
|
|
271
|
+
n = 0
|
|
272
|
+
while True:
|
|
273
|
+
try:
|
|
274
|
+
_osop(os.mkdir, self.lockpath)
|
|
275
|
+
break
|
|
276
|
+
except oserrors[errno.EEXIST]:
|
|
277
|
+
from time import sleep
|
|
278
|
+
sleep(.01 if n < 10 else .1)
|
|
279
|
+
n += 1
|
|
280
|
+
try:
|
|
281
|
+
yield listorempty(self.directory, CompactVenv, lambda n: n.startswith(self.prefix))
|
|
282
|
+
finally:
|
|
283
|
+
os.rmdir(self.lockpath)
|
|
284
|
+
|
|
285
|
+
@contextmanager
|
|
286
|
+
def _transient(self, installdeps):
|
|
287
|
+
log.info('Create new venv.')
|
|
288
|
+
with TemporaryDirectory() as venvpath:
|
|
289
|
+
venv = CompactVenv(venvpath)
|
|
290
|
+
venv.create(installdeps.uv)
|
|
291
|
+
installdeps.invoke(venv)
|
|
292
|
+
assert venv.compatible(installdeps) # Bug if not.
|
|
293
|
+
yield venv
|
|
294
|
+
|
|
295
|
+
@contextmanager
|
|
296
|
+
def readonly(self, installdeps):
|
|
297
|
+
with self._lock() as venvs:
|
|
298
|
+
shuffle(venvs)
|
|
299
|
+
for venv in venvs:
|
|
300
|
+
if venv.compatible(installdeps):
|
|
301
|
+
break
|
|
302
|
+
else:
|
|
303
|
+
venv = None
|
|
304
|
+
if venv is None:
|
|
305
|
+
log.info('Create new venv.')
|
|
306
|
+
temp = CompactVenv(mkdtemp(dir = self.directory))
|
|
307
|
+
try:
|
|
308
|
+
temp.create(installdeps.uv)
|
|
309
|
+
installdeps.invoke(temp)
|
|
310
|
+
with self._lock() as venvs:
|
|
311
|
+
venv = CompactVenv(mkdtemp(dir = self.directory, prefix = self.prefix))
|
|
312
|
+
with _onerror(venv.delete):
|
|
313
|
+
for name in os.listdir(temp.venvpath):
|
|
314
|
+
os.rename(os.path.join(temp.venvpath, name), os.path.join(venv.venvpath, name))
|
|
315
|
+
assert venv.compatible(installdeps) # Bug if not.
|
|
316
|
+
log.info("Compact %s venvs.", len(venvs) + 1)
|
|
317
|
+
subprocess.check_call(['jdupes', '--link-hard', '--recurse', '--quiet', '--param-order', *(u.venvpath for u in venvs), venv.venvpath])
|
|
318
|
+
finally:
|
|
319
|
+
temp.delete()
|
|
320
|
+
yield venv
|
|
321
|
+
|
|
322
|
+
@contextmanager
|
|
323
|
+
def readwrite(self, installdeps):
|
|
324
|
+
yield from self._transient()
|
|
325
|
+
|
|
326
|
+
class FastReq:
|
|
327
|
+
|
|
328
|
+
class Version:
|
|
329
|
+
|
|
330
|
+
def __init__(self, operator, splitversion):
|
|
331
|
+
self.operator = operator
|
|
332
|
+
self.splitversion = splitversion
|
|
333
|
+
|
|
334
|
+
def accept(self, splitversion):
|
|
335
|
+
def pad(v):
|
|
336
|
+
return v + [0] * (n - len(v))
|
|
337
|
+
versions = [splitversion, self.splitversion]
|
|
338
|
+
n = max(map(len, versions))
|
|
339
|
+
return self.operator(*map(pad, versions))
|
|
340
|
+
|
|
341
|
+
class DevSegment:
|
|
342
|
+
|
|
343
|
+
def __init__(self, n):
|
|
344
|
+
self.n = n
|
|
345
|
+
|
|
346
|
+
@classmethod
|
|
347
|
+
def tosplitversion(cls, versionstr, devprefix = 'dev'):
|
|
348
|
+
return [cls.DevSegment(int(k[len(devprefix):])) if k.startswith(devprefix) else int(k) for k in versionstr.split('.')]
|
|
349
|
+
|
|
350
|
+
s = r'\s*'
|
|
351
|
+
nameregex = '[A-Za-z0-9._-]+' # Slightly more lenient than PEP 508.
|
|
352
|
+
extras = r"\[{s}(?:{nameregex}{s}(?:,{s}{nameregex}{s})*)?]".format(**locals())
|
|
353
|
+
version = "(<|<=|!=|==|>=|>){s}([0-9.]+(?:[.]dev[0-9]+)?)".format(**locals()) # Subset of features.
|
|
354
|
+
versionregex = "^{s}{version}{s}$".format(**locals())
|
|
355
|
+
getregex = "^{s}({nameregex}){s}({extras}{s})?({version}{s}(?:,{s}{version}{s})*)?$".format(**locals())
|
|
356
|
+
skipregex = "^{s}(?:#|$)".format(**locals())
|
|
357
|
+
del s, extras, version
|
|
358
|
+
operators = {
|
|
359
|
+
'<': operator.lt,
|
|
360
|
+
'<=': operator.le,
|
|
361
|
+
'!=': operator.ne,
|
|
362
|
+
'==': operator.eq,
|
|
363
|
+
'>=': operator.ge,
|
|
364
|
+
'>': operator.gt,
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
@classmethod
|
|
368
|
+
def parselines(cls, lines):
|
|
369
|
+
def g():
|
|
370
|
+
for line in lines:
|
|
371
|
+
if re.search(cls.skipregex, line) is not None:
|
|
372
|
+
continue
|
|
373
|
+
namepart, extras, versionspec = re.search(cls.getregex, line).groups()[:3]
|
|
374
|
+
extras = () if extras is None else tuple(sorted(set(re.findall(cls.nameregex, extras)))) # TODO LATER: Normalisation.
|
|
375
|
+
versions = []
|
|
376
|
+
reqstrversions = []
|
|
377
|
+
if versionspec is not None:
|
|
378
|
+
for onestr in versionspec.split(','):
|
|
379
|
+
operatorstr, versionstr = re.search(cls.versionregex, onestr).groups()
|
|
380
|
+
versions.append(cls.Version(cls.operators[operatorstr], cls.tosplitversion(versionstr)))
|
|
381
|
+
reqstrversions.append(operatorstr + versionstr)
|
|
382
|
+
yield cls(namepart, extras, versions, namepart + ("[%s]" % ','.join(extras) if extras else '') + ','.join(sorted(reqstrversions)))
|
|
383
|
+
return list(g())
|
|
384
|
+
|
|
385
|
+
def __init__(self, namepart, extras, versions, reqstr):
|
|
386
|
+
self.namepart = namepart
|
|
387
|
+
self.extras = extras
|
|
388
|
+
self.versions = versions
|
|
389
|
+
self.reqstr = reqstr
|
|
390
|
+
|
|
391
|
+
def acceptversion(self, versionstr):
|
|
392
|
+
splitversion = self.tosplitversion(versionstr)
|
|
393
|
+
return all(v.accept(splitversion) for v in self.versions)
|
|
394
|
+
|
|
395
|
+
class ParsedRequires:
|
|
396
|
+
|
|
397
|
+
parselines = staticmethod(FastReq.parselines)
|
|
398
|
+
|
|
399
|
+
def __init__(self, requires, uv):
|
|
400
|
+
self.pypireqs = self.parselines(requires)
|
|
401
|
+
self.uv = uv
|
|
402
|
+
|
|
403
|
+
def invoke(self, venv):
|
|
404
|
+
venv.install([r.reqstr for r in self.pypireqs], self.uv)
|
|
405
|
+
|
|
406
|
+
def poplocalreqs(self, workspace):
|
|
407
|
+
projectdirs = {}
|
|
408
|
+
for projectdir in (os.path.join(workspace, n) for n in os.listdir(workspace)):
|
|
409
|
+
if os.path.isdir(projectdir):
|
|
410
|
+
eggdirnames = [n for n in os.listdir(projectdir) if n.endswith('.egg-info')]
|
|
411
|
+
if 1 == len(eggdirnames):
|
|
412
|
+
with open(os.path.join(projectdir, eggdirnames[0], 'PKG-INFO'), encoding = 'utf-8') as f:
|
|
413
|
+
try:
|
|
414
|
+
parser
|
|
415
|
+
except NameError:
|
|
416
|
+
from email.parser import Parser
|
|
417
|
+
parser = Parser()
|
|
418
|
+
name = parser.parse(f)['Name']
|
|
419
|
+
if name is not None:
|
|
420
|
+
projectdirs[name] = projectdir
|
|
421
|
+
local = OrderedDict()
|
|
422
|
+
reqs = list(self.pypireqs)
|
|
423
|
+
del self.pypireqs[:]
|
|
424
|
+
while reqs:
|
|
425
|
+
nextreqs = []
|
|
426
|
+
for req in reqs:
|
|
427
|
+
projectdir = projectdirs.get(req.namepart)
|
|
428
|
+
if projectdir is None:
|
|
429
|
+
self.pypireqs.append(req)
|
|
430
|
+
elif projectdir not in local:
|
|
431
|
+
requirementslinesanduv = _getrequirementslinesanduvornone(projectdir, req.extras)
|
|
432
|
+
if requirementslinesanduv is None:
|
|
433
|
+
raise NoRequirementsFoundException("%s[%s]" % (projectdir, ','.join(req.extras)))
|
|
434
|
+
nextreqs.extend(self.parselines(requirementslinesanduv[0]))
|
|
435
|
+
local[projectdir] = None
|
|
436
|
+
reqs = nextreqs
|
|
437
|
+
return list(local)
|
|
438
|
+
|
|
439
|
+
def _getrequirementslinesanduvornone(projectdir, extras, metadataspec = FastReq.Version(operator.ge, [1, 2])):
|
|
440
|
+
def linesornone(acceptnull, *names):
|
|
441
|
+
path = os.path.join(projectdir, *names)
|
|
442
|
+
if os.path.exists(path):
|
|
443
|
+
log.debug("Found requirements: %s", path)
|
|
444
|
+
with open(path) as f:
|
|
445
|
+
return f.read().splitlines()
|
|
446
|
+
if acceptnull:
|
|
447
|
+
log.debug("Null requirements: %s", path)
|
|
448
|
+
return []
|
|
449
|
+
if extras:
|
|
450
|
+
log.warning("Ignore extras %s in: %s", ','.join(extras), projectdir) # TODO: Find extra requirements as well.
|
|
451
|
+
v = linesornone(False, 'requirements.txt')
|
|
452
|
+
if v is not None:
|
|
453
|
+
return v, 'uv'
|
|
454
|
+
names = [name for name in os.listdir(projectdir) if name.endswith('.egg-info')]
|
|
455
|
+
if not names:
|
|
456
|
+
return
|
|
457
|
+
name, = names # XXX: Could there legitimately be multiple?
|
|
458
|
+
uv = os.path.join(projectdir, name, 'uv')
|
|
459
|
+
if os.path.exists(uv):
|
|
460
|
+
uv = os.path.realpath(uv)
|
|
461
|
+
log.debug("Custom uv: %s", uv)
|
|
462
|
+
else:
|
|
463
|
+
uv = 'uv'
|
|
464
|
+
path = os.path.join(projectdir, name, 'PKG-INFO')
|
|
465
|
+
with open(path, encoding = 'utf-8') as f:
|
|
466
|
+
from email.parser import Parser
|
|
467
|
+
message = Parser().parse(f)
|
|
468
|
+
if metadataspec.accept(FastReq.tosplitversion(message['Metadata-Version'])):
|
|
469
|
+
log.debug("Found requirements in: %s", path)
|
|
470
|
+
return message.get_all('Requires-Dist', []), uv
|
|
471
|
+
return linesornone(True, name, 'requires.txt'), uv
|
|
472
|
+
|
|
473
|
+
class ParserCommand:
|
|
474
|
+
|
|
475
|
+
@classmethod
|
|
476
|
+
def main(cls):
|
|
477
|
+
from argparse import ArgumentParser # Two or three hundredths.
|
|
478
|
+
logging.basicConfig(format = "%(asctime)s %(levelname)s %(message)s", level = logging.DEBUG)
|
|
479
|
+
parser = ArgumentParser(description = cls.help)
|
|
480
|
+
if cls.letter is not None:
|
|
481
|
+
parser.add_argument('-' + cls.letter, action = 'store_true', help = 'select this subcommand')
|
|
482
|
+
cls.initparser(parser)
|
|
483
|
+
parser.add_argument('-v', action = 'store_true', help = 'show debug logging')
|
|
484
|
+
args = parser.parse_args()
|
|
485
|
+
if cls.letter is not None:
|
|
486
|
+
assert getattr(args, cls.letter)
|
|
487
|
+
if not args.v:
|
|
488
|
+
logging.getLogger().setLevel(logging.INFO)
|
|
489
|
+
cls.mainimpl(args)
|
|
490
|
+
|
|
491
|
+
class NoRequirementsFoundException(Exception): pass
|
|
492
|
+
|
|
493
|
+
def _findrequirements(projectdir):
|
|
494
|
+
while True:
|
|
495
|
+
requirementslinesanduv = _getrequirementslinesanduvornone(projectdir, ())
|
|
496
|
+
if requirementslinesanduv is not None:
|
|
497
|
+
return projectdir, *requirementslinesanduv
|
|
498
|
+
parent = os.path.dirname(projectdir)
|
|
499
|
+
if parent == projectdir:
|
|
500
|
+
raise NoRequirementsFoundException
|
|
501
|
+
projectdir = parent
|
|
502
|
+
|
|
503
|
+
def checkpath(projectdir, path):
|
|
504
|
+
while True:
|
|
505
|
+
path = os.path.dirname(path)
|
|
506
|
+
if path == projectdir:
|
|
507
|
+
return True
|
|
508
|
+
if not os.path.exists(os.path.join(path, '__init__.py')): # XXX: What about namespace packages?
|
|
509
|
+
break
|
|
510
|
+
|
|
511
|
+
def commandornone(srcpath):
|
|
512
|
+
name = os.path.basename(srcpath)
|
|
513
|
+
name = os.path.basename(os.path.dirname(srcpath)) if '__init__.py' == name else name[:-len(dotpy)]
|
|
514
|
+
if '-' not in name:
|
|
515
|
+
return name.replace('_', '-')
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'augment interpreter environment and exec module for internal use only'
|
|
2
|
+
import os, runpy, sys
|
|
3
|
+
|
|
4
|
+
def _insertionpoint(v, suffix = os.sep + 'site-packages'):
|
|
5
|
+
i = n = len(v)
|
|
6
|
+
while not v[i - 1].endswith(suffix):
|
|
7
|
+
i -= 1
|
|
8
|
+
if not i:
|
|
9
|
+
return n
|
|
10
|
+
while i and v[i - 1].endswith(suffix):
|
|
11
|
+
i -= 1
|
|
12
|
+
return i
|
|
13
|
+
|
|
14
|
+
def _decompress(paths):
|
|
15
|
+
i = iter(paths)
|
|
16
|
+
prefix = next(i)
|
|
17
|
+
try:
|
|
18
|
+
while True:
|
|
19
|
+
yield prefix + next(i)
|
|
20
|
+
except StopIteration:
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
def main():
|
|
24
|
+
sys.path[0] = bindir = os.path.dirname(sys.executable)
|
|
25
|
+
try:
|
|
26
|
+
envpath = os.environ['PATH']
|
|
27
|
+
except KeyError:
|
|
28
|
+
envpath = bindir
|
|
29
|
+
else:
|
|
30
|
+
envpath = bindir + os.pathsep + envpath
|
|
31
|
+
os.environ['PATH'] = envpath
|
|
32
|
+
sys.path[slice(*[_insertionpoint(sys.path)] * 2)] = _decompress(sys.argv.pop(1).split(os.pathsep))
|
|
33
|
+
exec(sys.argv.pop(1))
|
|
34
|
+
runpy.run_module(sys.argv.pop(1), run_name = '__main__', alter_sys = True)
|
|
35
|
+
|
|
36
|
+
if ('__main__' == __name__):
|
|
37
|
+
main()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from . import CompactPool, dotpy, _findrequirements, ParsedRequires, ParserCommand
|
|
2
|
+
import os, sys
|
|
3
|
+
|
|
4
|
+
class Launch(ParserCommand):
|
|
5
|
+
|
|
6
|
+
help = 'launch a script with the interpreter and requirements it needs'
|
|
7
|
+
letter = None
|
|
8
|
+
|
|
9
|
+
@staticmethod
|
|
10
|
+
def initparser(parser):
|
|
11
|
+
parser.add_argument('--req', help = 'use the given requirement specifier only')
|
|
12
|
+
parser.add_argument('scriptpath', help = 'should be preceded by a -- arg')
|
|
13
|
+
parser.add_argument('scriptarg', nargs = '*', help = 'arguments for scriptpath')
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def mainimpl(cls, args):
|
|
17
|
+
try:
|
|
18
|
+
dd = sys.argv.index('--')
|
|
19
|
+
except ValueError:
|
|
20
|
+
scriptpath = args.scriptpath
|
|
21
|
+
scriptargs = args.scriptarg
|
|
22
|
+
else:
|
|
23
|
+
scriptpath = sys.argv[dd + 1]
|
|
24
|
+
scriptargs = sys.argv[dd + 2:]
|
|
25
|
+
assert scriptpath.endswith(dotpy)
|
|
26
|
+
reqstr = args.req
|
|
27
|
+
if reqstr is None:
|
|
28
|
+
scriptpath = os.path.abspath(scriptpath) # XXX: Is abspath safe when scriptpath has symlinks?
|
|
29
|
+
projectdir, requirementslines, uv = _findrequirements(os.path.dirname(scriptpath))
|
|
30
|
+
installdeps = ParsedRequires(requirementslines, uv)
|
|
31
|
+
localreqs = installdeps.poplocalreqs(os.path.normpath(os.path.join(projectdir, '..')))
|
|
32
|
+
localreqs.insert(0, projectdir)
|
|
33
|
+
module = os.path.relpath(scriptpath[:-len(dotpy)], projectdir).replace(os.sep, '.')
|
|
34
|
+
else:
|
|
35
|
+
installdeps = ParsedRequires([reqstr], 'uv')
|
|
36
|
+
localreqs = []
|
|
37
|
+
module = scriptpath[:-len(dotpy)].replace(os.sep, '.')
|
|
38
|
+
with CompactPool().readonly(installdeps) as venv:
|
|
39
|
+
venv.run('exec', localreqs, module, scriptargs)
|