pyven 98__py3-none-any.whl

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.
pyven/README.md.aridt ADDED
@@ -0,0 +1,30 @@
1
+ # $(name)
2
+ $(tagline)$try($.($(verbose_blank)
3
+
4
+ ## Install
5
+ These are generic installation instructions.
6
+
7
+ ### To use, permanently
8
+ The quickest way to get started is to install the current release from PyPI:
9
+ ```
10
+ pip$first$(pyversions) install --user $(name)
11
+ ```
12
+
13
+ ### To use, temporarily
14
+ If you prefer to keep .local clean, install to a virtualenv:
15
+ ```
16
+ python$first$(pyversions) -m venv venvname
17
+ venvname/bin/pip install -U pip
18
+ venvname/bin/pip install $(name)
19
+ . venvname/bin/activate
20
+ ```) $.())$try($join$list$first$map($(commands) $.[
21
+
22
+ ## Commands]) $.())$join$map($(commands) $.[
23
+
24
+ ### $(name)
25
+ $(doc)])$try($.(
26
+
27
+ ## API
28
+
29
+ $(pydoc)$hole$.(
30
+ )) $.())
pyven/__init__.py ADDED
@@ -0,0 +1 @@
1
+ # This file blank.
pyven/bdist.py ADDED
@@ -0,0 +1,36 @@
1
+ from argparse import ArgumentParser
2
+ from glob import iglob
3
+ from tempfile import mkdtemp
4
+ import logging, os, shutil, subprocess
5
+
6
+ log = logging.getLogger(__name__)
7
+ distdir = 'dist'
8
+
9
+ def main():
10
+ logging.basicConfig(format = "<%(levelname)s> %(message)s", level = logging.DEBUG)
11
+ parser = ArgumentParser()
12
+ parser.add_argument('--plat', required = True)
13
+ parser.add_argument('pyversions', nargs = '+')
14
+ args = parser.parse_args()
15
+ holder = mkdtemp()
16
+ try:
17
+ for pip in sorted(iglob("/opt/python/cp[%s]*/bin/pip" % ''.join(args.pyversions))):
18
+ compatibility = pip.split(os.sep)[3]
19
+ log.info("Make wheel(s) for implementation-ABI: %s", compatibility)
20
+ try:
21
+ subprocess.check_call([pip, '--no-cache-dir', 'wheel', '--no-deps', '-w', holder, '.'])
22
+ except subprocess.CalledProcessError:
23
+ log.warning('Skip compatibility:', exc_info = True)
24
+ continue
25
+ wheelpath, = (os.path.join(holder, n) for n in os.listdir(holder))
26
+ subprocess.check_call(['auditwheel', 'repair', '--plat', args.plat, '-w', distdir, wheelpath])
27
+ plaintarget = os.path.join(distdir, os.path.basename(wheelpath))
28
+ if os.path.exists(plaintarget):
29
+ log.info("Replace plain wheel: %s", plaintarget)
30
+ shutil.copy2(wheelpath, distdir)
31
+ os.remove(wheelpath)
32
+ finally:
33
+ shutil.rmtree(holder)
34
+
35
+ if ('__main__' == __name__):
36
+ main()
pyven/checks.py ADDED
@@ -0,0 +1,257 @@
1
+ from .divcheck import commentregex
2
+ from .files import Files
3
+ from .pipify import InstallDeps
4
+ from .projectinfo import ProjectInfo, SimpleInstallDeps
5
+ from .util import bgcontainer, Excludes, initapt, pyversiontags, stderr
6
+ from argparse import ArgumentParser
7
+ from aridity.config import ConfigCtrl
8
+ from aridity.util import NoSuchPathException, openresource
9
+ from diapyr.util import singleton
10
+ from itertools import chain
11
+ from lagoon import diff
12
+ from lagoon.program import NOEOL, partial
13
+ from setuptools import find_packages
14
+ from shutil import copytree, ignore_patterns
15
+ from tempfile import NamedTemporaryFile
16
+ from venvpool import dotpy, initlogging, Pool, Task, TemporaryDirectory
17
+ import logging, os, re, shutil, subprocess, sys
18
+
19
+ log = logging.getLogger(__name__)
20
+ skip = object()
21
+
22
+ @singleton
23
+ class yesno:
24
+
25
+ d = dict(no = False, yes = True)
26
+
27
+ def __call__(self, s):
28
+ return self.d[s]
29
+
30
+ def _localrepo():
31
+ cc = ConfigCtrl()
32
+ cc.loadsettings()
33
+ return cc.node.buildbot.repo
34
+
35
+ def _runcheck(variant, check, *args):
36
+ sys.stderr.write("%s[%s]: " % (check.__name__, variant))
37
+ sys.stderr.flush()
38
+ stderr('SKIP' if check(*args) is skip else 'OK')
39
+
40
+ class EveryVersion:
41
+
42
+ def __init__(self, info, siblings, userepo, noseargs, docker, transient):
43
+ self.files = Files(info.projectdir)
44
+ self.info = info
45
+ self.siblings = siblings
46
+ self.userepo = userepo
47
+ self.noseargs = noseargs
48
+ self.docker = docker
49
+ self.transient = transient
50
+
51
+ def allchecks(self):
52
+ for check in self.licheck, self.nlcheck, self.execcheck, self.divcheck, self.pyflakes, self.nose, self.readme, self.github, self.linktree:
53
+ check()
54
+
55
+ def licheck(self):
56
+ from .licheck import licheck
57
+ def g():
58
+ excludes = Excludes(self.info.config.licheck.exclude.globs)
59
+ for path in self.files.allsrcpaths:
60
+ if os.path.relpath(path, self.files.root) not in excludes:
61
+ yield path
62
+ _runcheck('*', licheck, self.info, list(g()))
63
+
64
+ def nlcheck(self):
65
+ from .nlcheck import nlcheck
66
+ _runcheck('*', nlcheck, self.files.allsrcpaths)
67
+
68
+ def execcheck(self):
69
+ from .execcheck import execcheck
70
+ _runcheck('*', execcheck, self.files.pypaths)
71
+
72
+ def divcheck(self):
73
+ from . import divcheck
74
+ scriptpath = divcheck.__file__
75
+ def divcheck():
76
+ if pyversion >= 3:
77
+ return skip
78
+ subprocess.check_call(["python%s" % pyversion, scriptpath] + self.files.pypaths)
79
+ for pyversion in self.info.config.pyversions:
80
+ _runcheck(pyversion, divcheck)
81
+
82
+ def pyflakes(self):
83
+ paths = [path for excludes in [Excludes(self.info.config.flakes.exclude.globs)]
84
+ for path in self.files.pypaths if os.path.relpath(path, self.files.root) not in excludes]
85
+ def pyflakes():
86
+ if paths:
87
+ with Pool(pyversion).readonlyortransient[self.transient](SimpleInstallDeps(['pyflakes'])) as venv:
88
+ venv.run('check_call', [], 'pyflakes', paths)
89
+ for pyversion in self.info.config.pyversions:
90
+ _runcheck(pyversion, pyflakes)
91
+
92
+ def nose(self):
93
+ upstream_devel_packages = list(self.info.config.upstream.devel.packages)
94
+ upstream_devel_scripts = list(self.info.config.upstream.devel.scripts) if self.userepo else []
95
+ with InstallDeps(self.info, self.siblings, _localrepo() if self.userepo else None) as installdeps:
96
+ installdeps.add('nose-cov', *self.info.config.test.requires) # TODO: Facility to freeze test requires tree.
97
+ for pyversion in self.info.config.pyversions:
98
+ reportsdir = os.path.join(self.info.projectdir, 'var', str(pyversion))
99
+ os.makedirs(reportsdir, exist_ok = True)
100
+ xmlpath = os.path.join(reportsdir, 'nosetests.xml')
101
+ if self.docker:
102
+ coveragepath = os.path.join(self.info.projectdir, '.coverage')
103
+ with bgcontainer('-v', "{0}:{0}".format('/var/run/docker.sock'), '--network', 'host', '-v', "%s:%s" % (os.path.abspath(self.info.projectdir), Container.workdir), "python:%s" % pyversiontags[pyversion][0]) as container:
104
+ container = Container(container)
105
+ container.cp(installdeps.workspace, 'installdeps')
106
+ container.inituser()
107
+ if upstream_devel_packages:
108
+ container.initapt()
109
+ for command in ['apt-get', 'update'], ['apt-get', 'install', '-y', 'sudo'] + upstream_devel_packages:
110
+ container.call(command, check = True, root = True)
111
+ for script in upstream_devel_scripts:
112
+ from lagoon import docker
113
+ dirpath = docker[NOEOL]('exec', container.container, 'mktemp', '-d') # No need to cleanup, will die with container.
114
+ log.debug("In container dir %s run script: %s", dirpath, script)
115
+ docker.exec[print]('-w', dirpath, '-t', container.container, 'sh', '-c', script)
116
+ installdeps.cinvoke(container)
117
+ cpath = lambda p: os.path.relpath(p, self.info.projectdir).replace(os.sep, '/')
118
+ status = container.call([
119
+ 'nosetests', '--exe', '-v',
120
+ '--with-doctest', '--doctest-extension', '.md',
121
+ '--with-xunit', '--xunit-file', cpath(xmlpath),
122
+ '--with-cov', '--cov-report', 'term-missing',
123
+ ] + sum((['--cov', p] for p in chain(find_packages(self.info.projectdir), self.info.py_modules())), []) + [cpath(p) for p in self.files.testpaths(xmlpath)] + self.noseargs)
124
+ else:
125
+ coveragepath = '.coverage'
126
+ with Pool(pyversion).readonlyortransient[self.transient](installdeps) as venv:
127
+ status = venv.run('call', installdeps.localreqs, Task('''import collections
128
+ try:
129
+ collections.Callable
130
+ except AttributeError:
131
+ from collections.abc import Callable
132
+ collections.Callable = Callable''', 'nose'), [
133
+ '--exe', '-v',
134
+ '--with-doctest', '--doctest-extension', '.md',
135
+ '--with-xunit', '--xunit-file', xmlpath,
136
+ '--with-cov', '--cov-report', 'term-missing',
137
+ ] + sum((['--cov', p] for p in chain(find_packages(self.info.projectdir), self.info.py_modules())), []) + self.files.testpaths(xmlpath) + self.noseargs)
138
+ if os.path.exists(coveragepath):
139
+ shutil.copy2(coveragepath, os.path.join(reportsdir, 'coverage')) # Replace whatever the status, as if we configured the location.
140
+ os.remove(coveragepath) # Can't simply use rename cross-device in release case.
141
+ assert not status
142
+
143
+ def readme(self):
144
+ def first(scope, resolvable):
145
+ for _, o in resolvable.resolve(scope).resolveditems():
146
+ return o
147
+ raise NoSuchPathException('Empty set.')
148
+ def getpydoc(mainmodules):
149
+ from lagoon import pydoc_markdown
150
+ with TemporaryDirectory() as pydocparent:
151
+ pydocdir = os.path.join(pydocparent, 'project')
152
+ copytree(self.info.projectdir, pydocdir, ignore = ignore_patterns('test_*'))
153
+ internal = {(os.path.dirname(mm.relpath) if '__init__.py' == os.path.basename(mm.relpath) else mm.relpath[:-len(dotpy)]).replace(os.sep, '.') for mm in mainmodules}
154
+ internal.update(self.info.config.internal_module)
155
+ modules = []
156
+ for dirpath, dirnames, filenames in os.walk(pydocdir):
157
+ for name in filenames:
158
+ if name.endswith(dotpy):
159
+ pypath = os.path.join(dirpath, name)
160
+ with open(pypath, 'r+') as f:
161
+ text = f.read()
162
+ cleantext = re.sub(commentregex, '', text, flags = re.MULTILINE)
163
+ if cleantext != text:
164
+ f.seek(0)
165
+ f.write(cleantext)
166
+ f.truncate()
167
+ modules.append(os.path.relpath(dirpath if '__init__.py' == name else pypath[:-len(dotpy)], pydocdir).replace(os.sep, '.'))
168
+ acc = re.sub('^#', '###', pydoc_markdown('--search-path', pydocdir), flags = re.MULTILINE)
169
+ acc = re.split('(?=^<a id="(?:%s)")' % '|'.join(map(re.escape, modules)), acc, flags = re.MULTILINE) # Module names are markup attribute-safe.
170
+ return ''.join(sorted(block for block in acc if block and re.search('"([^"]+)', block).group(1) not in internal))
171
+ def readme():
172
+ if not (self.info.config.github.participant or self.info.config.pypi.participant):
173
+ return skip
174
+ config = (-self.info.config).childctrl().node
175
+ config.first = first
176
+ if self.info.config.readme_verbose:
177
+ config.verbose_blank = ''
178
+ (-config).execute('commands * name = $label()')
179
+ mainmodules = sorted(self.info.mainmodules(), key = lambda mm: mm.command)
180
+ undocumented = [mm.command for mm in mainmodules if mm.doc is None]
181
+ if undocumented:
182
+ raise Exception("Undocumented: %s" % undocumented)
183
+ for mm in mainmodules:
184
+ (-config).printf("commands %s doc = %s", mm.command, mm.doc)
185
+ if self.info.config.pydoc_enabled:
186
+ config.pydoc = getpydoc(mainmodules)
187
+ with NamedTemporaryFile('w') as g:
188
+ with openresource(__name__, 'README.md.aridt') as f:
189
+ (-config).processtemplate(f, g)
190
+ g.flush()
191
+ completed = diff(g.name, os.path.join(self.info.projectdir, 'README.md'), check = False)
192
+ sys.stdout.write(completed.stdout)
193
+ assert completed.returncode in {0, 1}
194
+ assert all('<' != l[0] for l in completed.stdout.splitlines())
195
+ _runcheck('*', readme)
196
+
197
+ def github(self):
198
+ def github():
199
+ if not self.info.config.github.participant:
200
+ return skip
201
+ description, _ = self.info.descriptionandurl()
202
+ assert self.info.config.tagline == description
203
+ _runcheck('*', github)
204
+
205
+ def linktree(self):
206
+ def linktree():
207
+ account = self.info.config.linktree.account
208
+ if account is None:
209
+ return skip
210
+ from urllib.request import urlopen
211
+ from xml.sax.saxutils import escape
212
+ with urlopen("https://linktr.ee/%s" % account) as f: # TODO: Percent-encode.
213
+ assert ">%s \N{BULLET} %s<" % tuple(map(escape, [self.info.config.name, self.info.config.tagline])) in f.read().decode('utf-8') # TODO: Deduce encoding, consider lagoon URL.
214
+ _runcheck('*', linktree)
215
+
216
+ class Container:
217
+
218
+ workdir = '/io'
219
+
220
+ def __init__(self, container):
221
+ from lagoon import id
222
+ self.uid = int(id._u())
223
+ self.gid = int(id._g())
224
+ self.container = container
225
+
226
+ def inituser(self):
227
+ from lagoon import docker
228
+ docker('exec', self.container, 'groupadd', '-g', os.stat('/var/run/docker.sock').st_gid, 'docker', stdout = None)
229
+ docker('exec', self.container, 'groupadd', '-g', self.gid, 'pyvengroup', stdout = None)
230
+ docker('exec', self.container, 'useradd', '-g', self.gid, '-G', 'docker', '-u', self.uid, '-m', 'pyvenuser', stdout = None)
231
+
232
+ def initapt(self):
233
+ from lagoon import docker
234
+ initapt(docker[partial]('exec', self.container, stdout = None))
235
+
236
+ def install(self, args):
237
+ from lagoon import docker
238
+ if args:
239
+ docker('exec', '-w', self.workdir, self.container, 'pip', 'install', *args, stdout = None)
240
+
241
+ def call(self, args, check = False, root = False):
242
+ from lagoon import docker
243
+ return docker('exec', '-w', self.workdir, self.container, *([] if root else ['sudo', '-u', 'pyvenuser']) + args, stdout = None, check = check)
244
+
245
+ def cp(self, src, dest):
246
+ from lagoon import docker
247
+ docker.cp[print](src, f"{self.container}:{dest}")
248
+
249
+ def main():
250
+ initlogging()
251
+ parser = ArgumentParser()
252
+ parser.add_argument('--docker', action = 'store_true')
253
+ parser.add_argument('--repo', type = yesno, default = True)
254
+ parser.add_argument('--siblings', type = yesno, default = True)
255
+ parser.add_argument('--transient', action = 'store_true')
256
+ args, noseargs = parser.parse_known_args()
257
+ EveryVersion(ProjectInfo.seekany('.'), args.siblings, args.repo, noseargs, args.docker, args.transient).allchecks()
pyven/divcheck.py ADDED
@@ -0,0 +1,19 @@
1
+ import ast, re, sys
2
+
3
+ commentregex = ' \N{NUMBER SIGN} .+'
4
+
5
+ def main():
6
+ for path in sys.argv[1:]:
7
+ with open(path) as f:
8
+ text = f.read()
9
+ for node in ast.walk(ast.parse(text)):
10
+ if 'Div' == type(node).__name__:
11
+ hasdiv = True
12
+ break
13
+ else:
14
+ hasdiv = False
15
+ if hasdiv == (re.search("^from __future__ import division(?:%s)?$" % commentregex, text, flags = re.MULTILINE) is None):
16
+ raise Exception(path)
17
+
18
+ if ('__main__' == __name__):
19
+ main()
pyven/drmake.py ADDED
@@ -0,0 +1,11 @@
1
+ 'Build a Docker image with automatic tag.'
2
+ from .projectinfo import ProjectInfo
3
+ import os
4
+
5
+ def main():
6
+ info = ProjectInfo.seek('.')
7
+ command = 'docker', 'build', '-t', info.config.docker.tag, info.projectdir
8
+ os.execvp(command[0], command)
9
+
10
+ if '__main__' == __name__:
11
+ main()
pyven/execcheck.py ADDED
@@ -0,0 +1,21 @@
1
+ import os
2
+
3
+ execmask = 0x49
4
+ magic = '#!'
5
+
6
+ def execcheck(paths):
7
+ for path in paths:
8
+ basename = os.path.basename(path)
9
+ executable = bool(os.stat(path).st_mode & execmask)
10
+ with open(path) as f:
11
+ hasmagic = f.readline().startswith(magic)
12
+ if basename.lower().startswith('test'):
13
+ if not basename.startswith('test_'):
14
+ raise Exception("Inconsistent name: %s" % path) # Note pyflakes already checks for duplicate method names.
15
+ if executable:
16
+ raise Exception("Should not be executable: %s" % path)
17
+ if hasmagic:
18
+ raise Exception("Using %s is obsolete: %s" % (magic, path))
19
+ else:
20
+ if executable != hasmagic:
21
+ raise Exception(path)
pyven/files.py ADDED
@@ -0,0 +1,70 @@
1
+ from .util import stripeol
2
+ from collections import defaultdict
3
+ import os, subprocess, xml.dom.minidom as dom
4
+
5
+ class Files:
6
+
7
+ @staticmethod
8
+ def _findfiles(walkpath, suffixes, prefixes):
9
+ def acceptname():
10
+ for suffix in suffixes:
11
+ if name.endswith(suffix):
12
+ return True
13
+ for prefix in prefixes:
14
+ if name.startswith(prefix):
15
+ return True
16
+ prefixlen = len(walkpath + os.sep)
17
+ for dirpath, dirnames, filenames in os.walk(walkpath):
18
+ for name in sorted(filenames):
19
+ if acceptname():
20
+ yield os.path.join(dirpath, name)[prefixlen:]
21
+ dirnames.sort()
22
+
23
+ @classmethod
24
+ def relpaths(cls, root, suffixes, prefixes):
25
+ paths = list(cls._findfiles(root, suffixes, prefixes))
26
+ with open(os.devnull) as devnull:
27
+ if not subprocess.call(['hg', 'root'], stdout = devnull, stderr = devnull, cwd = root):
28
+ badstatuses = set('IR ')
29
+ for line in subprocess.Popen(['hg', 'st', '-A'] + paths, stdout = subprocess.PIPE, cwd = root).stdout:
30
+ line = stripeol(line).decode()
31
+ if line[0] not in badstatuses:
32
+ yield line[2:]
33
+ else:
34
+ if os.path.exists(os.path.join(root, '.gitmodules')):
35
+ for submoduleslash in (l.split(' ', 1)[1] + os.sep for l in subprocess.check_output(['git', 'config', '--file', '.gitmodules', '--get-regexp', '^submodule[.].+[.]path$'], cwd = root).decode().splitlines()):
36
+ paths = [p for p in paths if not p.startswith(submoduleslash)]
37
+ if paths:
38
+ p = subprocess.Popen(['git', 'check-ignore'] + paths, stdout = subprocess.PIPE, cwd = root)
39
+ ignored = set(p.communicate()[0].decode().splitlines())
40
+ assert p.wait() in [0, 1]
41
+ for path in paths:
42
+ if path not in ignored:
43
+ yield path
44
+
45
+ def __init__(self, root):
46
+ srcsuffixes = sum(([s, "%s.aridt" % s] for s in ['.py', '.py3', '.pyx', '.s', '.sh', '.h', '.cpp', '.cxx', '.arid', '.gradle', '.java', '.mk', '.md']), [])
47
+ self.allsrcpaths = [os.path.join(root, p) for p in self.relpaths(root, srcsuffixes, ['Dockerfile', 'Makefile'])]
48
+ self.docpaths = [p for p in self.allsrcpaths if p.endswith('.md')]
49
+ self.pypaths = [p for p in self.allsrcpaths if p.endswith('.py')]
50
+ self.root = root
51
+
52
+ def testpaths(self, reportpath):
53
+ paths = [p for p in self.pypaths if os.path.basename(p).startswith('test_')] + self.docpaths
54
+ if os.path.exists(reportpath):
55
+ with open(reportpath) as f:
56
+ doc = dom.parse(f)
57
+ nametopath = dict([p[len(self.root + os.sep):-len('.py')].replace(os.sep, '.'), p] for p in paths)
58
+ pathtotime = defaultdict(int)
59
+ for e in doc.getElementsByTagName('testcase'):
60
+ name = e.getAttribute('classname')
61
+ while True:
62
+ i = name.rfind('.')
63
+ if -1 == i:
64
+ break
65
+ name = name[:i]
66
+ if name in nametopath:
67
+ pathtotime[nametopath[name]] += float(e.getAttribute('time'))
68
+ break
69
+ paths.sort(key = lambda p: pathtotime.get(p, float('inf')))
70
+ return paths
pyven/functions.py ADDED
@@ -0,0 +1,6 @@
1
+ from aridity.model import Function, wrap
2
+
3
+ def fwrap(scope, fresolvable):
4
+ def g(scope, *resolvables):
5
+ return wrap(fresolvable.resolve(scope).scalar(*(r.resolve(scope).scalar for r in resolvables)))
6
+ return Function(g)
pyven/launch.py ADDED
@@ -0,0 +1,23 @@
1
+ 'Run project using a suitable venv from the pool.'
2
+ from .pipify import InstallDeps
3
+ from .projectinfo import ProjectInfo
4
+ from argparse import ArgumentParser
5
+ from venvpool import initlogging, Pool
6
+ import subprocess, sys
7
+
8
+ def main(): # TODO: Retire in favour of venvpool module.
9
+ initlogging()
10
+ parser = ArgumentParser()
11
+ parser.add_argument('--build', action = 'store_true', help = 'rebuild native components')
12
+ args = parser.parse_args()
13
+ info = ProjectInfo.seekany('.')
14
+ _, objref = next(iter(info.console_scripts())).split('=') # XXX: Support more than just the first?
15
+ modulename, qname = objref.split(':')
16
+ with InstallDeps(info, False, None) as installdeps, Pool(sys.version_info.major).readonlyorreadwrite[args.build](installdeps) as venv:
17
+ if args.build:
18
+ venv.install(['--no-deps', '-e', info.projectdir]) # XXX: Can this be done without venv install?
19
+ status = subprocess.call([venv.programpath('python'), '-c', "from %s import %s; %s()" % (modulename, qname.split('.')[0], qname)])
20
+ sys.exit(status)
21
+
22
+ if '__main__' == __name__:
23
+ main()
pyven/licheck.py ADDED
@@ -0,0 +1,76 @@
1
+ import hashlib, os, re, shlex, sys
2
+
3
+ gpltemplate = """# Copyright %(years)s %(author)s
4
+
5
+ # This file is part of %(name)s.
6
+ #
7
+ # %(name)s is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation, either version 3 of the License, or
10
+ # (at your option) any later version.
11
+ #
12
+ # %(name)s is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with %(name)s. If not, see <http://www.gnu.org/licenses/>.
19
+ """
20
+ intersection = '''# This file incorporates work covered by the following copyright and
21
+ # permission notice:
22
+ '''
23
+
24
+ def _hassuffix(name, *suffixes):
25
+ return name.endswith(suffixes) or name.endswith(tuple("%s.aridt" % s for s in suffixes))
26
+
27
+ def _checkmd5(info, name, expected):
28
+ licpath = os.path.join(info.projectdir, name)
29
+ md5 = hashlib.md5()
30
+ with open(licpath) as f:
31
+ md5.update(f.read().encode('utf_8'))
32
+ if expected != md5.hexdigest():
33
+ raise Exception(licpath)
34
+
35
+ def licheck(info, paths):
36
+ if not info.config.licheck.enabled:
37
+ sys.stderr.write('SKIP ')
38
+ return
39
+ sections = []
40
+ for name in info.config.licenses:
41
+ if sections:
42
+ sections.append(intersection)
43
+ if 'GPL' == name:
44
+ sections.append(gpltemplate % {
45
+ 'years': ', '.join(str(y) for y in info.config.years),
46
+ 'author': info.config.author,
47
+ 'name': info.config.name,
48
+ })
49
+ elif 'MIT' == name:
50
+ with open(info.mitpath()) as f:
51
+ sections.append(''.join(('# ' if l.rstrip() else '#') + l for l in f))
52
+ elif 'UNLICENSE' == name:
53
+ pass
54
+ else:
55
+ raise Exception(name)
56
+ master = ''.join(s + '\n' for s in sections) # Check each section ends with 2 newlines.
57
+ def checkone(path):
58
+ with open(path) as f:
59
+ text = f.read()
60
+ if text.startswith('#!'):
61
+ for _ in range(2):
62
+ text = text[text.index('\n') + 1:]
63
+ if _hassuffix(path, '.s'):
64
+ text = re.sub('^;', '#', text, flags = re.MULTILINE)
65
+ elif _hassuffix(path, '.h', '.cpp', '.cxx', '.gradle', '.java'):
66
+ text = re.sub('^//', '#', text, flags = re.MULTILINE)
67
+ elif _hassuffix(path, '.arid'):
68
+ text = re.sub('^:', '#', text, flags = re.MULTILINE)
69
+ return master == text[:len(master)]
70
+ badpaths = [p for p in paths if not checkone(p)]
71
+ if badpaths:
72
+ raise Exception(' '.join(map(shlex.quote, badpaths)))
73
+ if 'GPL' in info.config.licenses:
74
+ _checkmd5(info, 'COPYING', 'd32239bcb673463ab874e80d47fae504')
75
+ if 'UNLICENSE' in info.config.licenses:
76
+ _checkmd5(info, 'UNLICENSE', '7246f848faa4e9c9fc0ea91122d6e680')
pyven/mainmodules.py ADDED
@@ -0,0 +1,57 @@
1
+ from venvpool import checkpath, commandornone, dotpy as extension, scriptregex
2
+ import ast, logging, os, re, sys
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ def _lastiflineno(text):
7
+ for i, l in reversed(list(enumerate(text.splitlines()))):
8
+ if re.search(scriptregex, l) is not None:
9
+ return 1 + i
10
+
11
+ def _funcpath(func):
12
+ v = []
13
+ while True:
14
+ try:
15
+ v.append(func.id)
16
+ return '.'.join(reversed(v))
17
+ except AttributeError:
18
+ v.append(func.attr)
19
+ func = func.value
20
+
21
+ def main():
22
+ logging.basicConfig()
23
+ paths = sys.argv[1:]
24
+ projectdir = paths.pop(0)
25
+ for relpath in paths:
26
+ fullpath = os.path.join(projectdir, relpath)
27
+ if not checkpath(projectdir, fullpath):
28
+ continue
29
+ with open(fullpath) as f:
30
+ text = f.read()
31
+ iflineno = _lastiflineno(text)
32
+ if iflineno is None:
33
+ continue
34
+ command = commandornone(fullpath)
35
+ if command is None:
36
+ continue
37
+ try:
38
+ m = ast.parse(text)
39
+ except SyntaxError:
40
+ log.warning("Skip: %s" % relpath, exc_info = True)
41
+ continue
42
+ result = dict(
43
+ command = command,
44
+ doc = ast.get_docstring(m),
45
+ relpath = relpath,
46
+ )
47
+ ifstatement, = (obj for obj in m.body if iflineno == obj.lineno)
48
+ expr, = ifstatement.body
49
+ call = expr.value
50
+ if call.args or call.keywords:
51
+ log.warning("Bad call: %s", command)
52
+ else:
53
+ result['console_script'] = "%s=%s:%s" % (command, relpath[:-len(extension)].replace(os.sep, '.'), _funcpath(call.func))
54
+ print(result)
55
+
56
+ if ('__main__' == __name__):
57
+ main()
pyven/minreqs.py ADDED
@@ -0,0 +1,10 @@
1
+ 'Print project.arid snippet pinning requires to their minimum allowed versions.'
2
+ from .projectinfo import ProjectInfo
3
+ from venvpool import initlogging
4
+
5
+ def main():
6
+ initlogging()
7
+ print("requires = $list(%s)" % ' '.join(r.minstr() for r in ProjectInfo.seek('.').parsedrequires()))
8
+
9
+ if '__main__' == __name__:
10
+ main()
pyven/nlcheck.py ADDED
@@ -0,0 +1,11 @@
1
+ import re
2
+
3
+ class MoreThanOneEolStyleException(Exception): pass
4
+
5
+ def nlcheck(paths):
6
+ for path in paths:
7
+ with open(path, 'rb') as f:
8
+ text = f.read().decode()
9
+ eols = set(re.findall(r'\r\n|[\r\n]', text))
10
+ if len(eols) > 1:
11
+ raise MoreThanOneEolStyleException(path)
pyven/patchpolicy.py ADDED
@@ -0,0 +1,21 @@
1
+ from itertools import chain
2
+ import glob, json
3
+
4
+ policyglobs = [
5
+ '/opt/_internal/*/lib/python3.7/site-packages/auditwheel/policy/policy.json',
6
+ '/opt/_internal/pipx/venvs/auditwheel/lib/python3.1?/site-packages/auditwheel/policy/manylinux-policy.json',
7
+ ]
8
+ syslibs = 'libasound.so.2', 'libjack.so.0', 'libportaudio.so.2'
9
+
10
+ def main():
11
+ policypath, = chain(*map(glob.iglob, policyglobs))
12
+ with open(policypath) as f:
13
+ policy = json.load(f)
14
+ for edition in policy:
15
+ if edition['name'].startswith('manylinux'):
16
+ edition['lib_whitelist'].extend(syslibs)
17
+ with open(policypath, 'w') as f:
18
+ json.dump(policy, f)
19
+
20
+ if ('__main__' == __name__):
21
+ main()