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/pipify.py ADDED
@@ -0,0 +1,161 @@
1
+ 'Generate setuptools files for a project.arid project.'
2
+ from .projectinfo import ProjectInfo, Req, SimpleInstallDeps
3
+ from argparse import ArgumentParser
4
+ from aridity.config import ConfigCtrl
5
+ from diapyr.util import bfs
6
+ from pkg_resources import resource_filename
7
+ from tempfile import mkdtemp
8
+ from venvpool import initlogging, Pool
9
+ import logging, os, shutil, subprocess, sys
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+ def pipify(info, version = None):
14
+ release = version is not None
15
+ # Allow release of project without origin:
16
+ if release:
17
+ if info.config.github.participant:
18
+ _, url = info.descriptionandurl()
19
+ elif info.config.pypi.participant:
20
+ url = "https://pypi.org/project/%s/" % info.config.name
21
+ else:
22
+ raise Exception
23
+ else:
24
+ url = None
25
+ cc = ConfigCtrl()
26
+ cc.execute('''py_modules := $list()
27
+ install_requires := $list()
28
+ console_scripts := $list()
29
+ ''')
30
+ cc.w.name = info.config.name
31
+ cc.w.tagline = info.config.tagline
32
+ for t in info.config.resource.types:
33
+ cc.w.resource.types += t
34
+ cc.w.version = version if release else info.devversion()
35
+ cc.w.description = info.config.tagline
36
+ cc.w.long_description = 'long_description()' if release else repr(None)
37
+ cc.w.url = url
38
+ cc.w.author = info.config.author if release else None
39
+ cc.w.author_email = info.config.author_email if release else None
40
+ for m in info.py_modules():
41
+ cc.w.py_modules += m
42
+ for r in info.allrequires:
43
+ cc.w.install_requires += r
44
+ for s in info.console_scripts():
45
+ cc.w.console_scripts += s
46
+ cc.w.universal = int({2, 3} <= set(info.config.pyversions))
47
+ # XXX: Use soak to generate these?
48
+ tasks = [
49
+ ['setup.py', 'setup.py.aridt', 'pystr'],
50
+ ['setup.cfg', 'setup.cfg.aridt', 'void'],
51
+ ]
52
+ @bfs(info.allbuildrequires)
53
+ def proc(bfsinfo, name):
54
+ cc.w.build_requires += name
55
+ if proc.donekeys != {'setuptools', 'wheel'}:
56
+ tasks.append(['pyproject.toml', 'pyproject.toml.aridt', 'tomlquote'])
57
+ for name, template, quote in tasks:
58
+ cc.printf('" = $(%s)', quote)
59
+ cc.processtemplate(
60
+ resource_filename(__name__, template), # TODO LATER: Make aridity get the resource.
61
+ os.path.abspath(os.path.join(info.projectdir, name)))
62
+
63
+ def main():
64
+ initlogging()
65
+ parser = ArgumentParser()
66
+ parser.add_argument('--transient', action = 'store_true')
67
+ parser.add_argument('--version')
68
+ parser.add_argument('projectdir', nargs = '?') # FIXME: When projectdir is passed in its console_scripts are not populated!
69
+ args = parser.parse_args()
70
+ info = ProjectInfo.seek('.') if args.projectdir is None else ProjectInfo(args.projectdir, os.path.join(args.projectdir, ProjectInfo.projectaridname))
71
+ pipify(info, args.version)
72
+ setupcommand(info, sys.version_info.major, args.transient, 'egg_info')
73
+
74
+ def setupcommand(info, pyversion, transient, *command):
75
+ def setup(absexecutable):
76
+ subprocess.check_call([absexecutable, 'setup.py'] + list(command), cwd = info.projectdir)
77
+ if {'setuptools', 'wheel'} == set(info.allbuildrequires) and sys.version_info.major == pyversion:
78
+ setup(sys.executable)
79
+ else:
80
+ with Pool(pyversion).readonlyortransient[transient](SimpleInstallDeps(info.allbuildrequires)) as venv:
81
+ setup(venv.programpath('python'))
82
+
83
+ class VolatileReq:
84
+
85
+ @property
86
+ def namepart(self):
87
+ return self.info.config.name
88
+
89
+ def __init__(self, info):
90
+ self.info = info
91
+
92
+ def acceptversion(self, versionstr):
93
+ return self.info.devversion() == versionstr
94
+
95
+ class InstallDeps:
96
+
97
+ @property
98
+ def pypireqs(self):
99
+ return [VolatileReq(i) for i in self.volatileprojects] + self.fetchreqs
100
+
101
+ def __init__(self, info, siblings, localrepo):
102
+ self.info = info
103
+ self.siblings = siblings
104
+ self.localrepo = localrepo
105
+
106
+ def __enter__(self):
107
+ self.workspace = mkdtemp()
108
+ editableprojects = {}
109
+ volatileprojects = {}
110
+ pypireqs = []
111
+ def adddeps(i, root):
112
+ for r in i.parsedrequires():
113
+ name = r.namepart
114
+ if name in editableprojects or name in volatileprojects:
115
+ continue
116
+ if self.siblings:
117
+ siblingpath = r.siblingpath(i.contextworkspace())
118
+ if os.path.exists(siblingpath):
119
+ editableprojects[name] = j = ProjectInfo.seek(siblingpath)
120
+ yield j, True
121
+ continue
122
+ if self.localrepo is not None:
123
+ repopath = os.path.join(self.localrepo, "%s.git" % name)
124
+ if os.path.exists(repopath):
125
+ if self.siblings:
126
+ log.warning("Not a sibling, install from repo: %s", name)
127
+ clonepath = os.path.join(self.workspace, name)
128
+ subprocess.check_call(['git', 'clone', '--depth', '1', "file://%s" % repopath, clonepath])
129
+ subprocess.check_call(['git', 'fetch', '--tags'], cwd = clonepath)
130
+ volatileprojects[name] = j = ProjectInfo.seek(clonepath)
131
+ yield j, False
132
+ continue
133
+ if root: # Otherwise pip will handle it.
134
+ pypireqs.append(r.reqstr)
135
+ @bfs([(self.info, True)])
136
+ class Proc:
137
+ def newdepth(self):
138
+ log.debug("Examine deps of: %s", ', '.join(i.config.name for i, _ in self.currentkeys))
139
+ def process(self, t):
140
+ return adddeps(*t)
141
+ for i in volatileprojects.values(): # Assume editables already pipified.
142
+ pipify(i)
143
+ self.localreqs = [i.projectdir for i in editableprojects.values()]
144
+ self.volatileprojects = volatileprojects.values()
145
+ self.fetchreqs = list(Req.published(pypireqs))
146
+ return self
147
+
148
+ def add(self, *requires):
149
+ self.fetchreqs.extend(Req.parselines(requires))
150
+
151
+ def invoke(self, venv):
152
+ venv.install([i.projectdir for i in self.volatileprojects] + [r.reqstr for r in self.fetchreqs])
153
+
154
+ def cinvoke(self, container):
155
+ container.install(["/installdeps/%s" % os.path.relpath(i.projectdir, self.workspace).replace(os.sep, '/') for i in self.volatileprojects] + [r.reqstr for r in self.fetchreqs])
156
+
157
+ def __exit__(self, *exc_info):
158
+ shutil.rmtree(self.workspace)
159
+
160
+ if '__main__' == __name__:
161
+ main()
pyven/projectinfo.arid ADDED
@@ -0,0 +1,36 @@
1
+ fwrap = $pyref(.functions fwrap)
2
+ neq := $fwrap$pyref(operator ne)
3
+ requires := $list()
4
+ pyversions := $list()
5
+ proprietary = false
6
+ resource types := $list(pxd pyx pyxbld arid aridt)
7
+ build requires +=
8
+ setuptools
9
+ wheel
10
+ licenses := $list(GPL)
11
+ MIT path = LICENSE
12
+ licheck
13
+ enabled = $¬$(proprietary)
14
+ exclude globs += **/*.md
15
+ flakes exclude globs := $list()
16
+ pypi
17
+ account = $(None)
18
+ participant = $neq($(account) $(None))
19
+ github
20
+ account = $(None)
21
+ participant = $neq($(account) $(None))
22
+ linktree account = $(None)
23
+ devel
24
+ packages := $list()
25
+ scripts := $list()
26
+ warmups := $list()
27
+ upstream devel
28
+ packages := $list()
29
+ scripts := $list()
30
+ test requires := $list()
31
+ tagline = $(void)
32
+ cython_build_version = 3.0.11
33
+ numpy_build_version = 2.0.2
34
+ pydoc_enabled = true
35
+ readme_verbose = $(github participant)
36
+ internal_module := $list()
pyven/projectinfo.py ADDED
@@ -0,0 +1,215 @@
1
+ from . import mainmodules
2
+ from .files import Files
3
+ from .util import Path
4
+ from aridity.config import ConfigCtrl
5
+ from aridity.model import Entry, Resource
6
+ from aridity.util import openresource
7
+ from inspect import getsource
8
+ from pkg_resources import parse_requirements
9
+ from setuphacks import getsetupkwargs
10
+ from venvpool import ParsedRequires, TemporaryDirectory
11
+ import logging, os, re, subprocess, venvpool
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ class ProjectInfoNotFoundException(Exception): pass
16
+
17
+ def textcontent(node):
18
+ def iterparts(node):
19
+ value = node.nodeValue
20
+ if value is None:
21
+ for child in node.childNodes:
22
+ for text in iterparts(child):
23
+ yield text
24
+ else:
25
+ yield value
26
+ return ''.join(iterparts(node))
27
+
28
+ class Req:
29
+
30
+ namematch = re.compile(r'\S+').search
31
+
32
+ @classmethod
33
+ def parselines(cls, lines):
34
+ return [cls(parsed) for parsed in parse_requirements(lines)]
35
+
36
+ @classmethod
37
+ def published(cls, reqstrs):
38
+ from http import HTTPStatus
39
+ from urllib.error import HTTPError
40
+ from urllib.parse import quote
41
+ from urllib.request import Request, urlopen
42
+ for r in cls.parselines(reqstrs):
43
+ try:
44
+ # FIXME: Allow running tests offline.
45
+ with urlopen(Request("https://pypi.org/simple/%s/" % quote(r.namepart, safe = ''), method = 'HEAD')):
46
+ pass
47
+ yield r
48
+ except HTTPError as e:
49
+ if e.code != HTTPStatus.NOT_FOUND:
50
+ raise
51
+ log.warning("Never published: %s", r.namepart)
52
+
53
+ @property
54
+ def namepart(self):
55
+ return self.parsed.name
56
+
57
+ @property
58
+ def extras(self):
59
+ return self.parsed.extras
60
+
61
+ @property
62
+ def reqstr(self):
63
+ return str(self.parsed)
64
+
65
+ @property
66
+ def specifierset(self):
67
+ return self.parsed.specifier
68
+
69
+ def __init__(self, parsed):
70
+ self.parsed = parsed
71
+
72
+ def acceptversion(self, versionstr):
73
+ return versionstr in self.parsed
74
+
75
+ def siblingpath(self, workspace):
76
+ return os.path.join(workspace, self.namepart)
77
+
78
+ def isproject(self, info):
79
+ return os.path.exists(self.siblingpath(info.contextworkspace()))
80
+
81
+ def minstr(self):
82
+ version, = (s.version for s in self.specifierset if s.operator in {'>=', '=='})
83
+ return "%s==%s" % (self.namepart, version)
84
+
85
+ def accept(self):
86
+ marker = self.parsed.marker
87
+ try:
88
+ if marker is None or marker.evaluate():
89
+ assert not self.parsed.extras # Not supported.
90
+ return True
91
+ except ValueError as e:
92
+ if 'UndefinedEnvironmentName' != type(e).__name__:
93
+ raise
94
+
95
+ def keyversion(self):
96
+ s, = self.specifierset
97
+ return self.parsed.key, s.version
98
+
99
+ class SimpleInstallDeps(ParsedRequires):
100
+
101
+ parselines = staticmethod(Req.parselines)
102
+
103
+ class ProjectInfo:
104
+
105
+ projectaridname = 'project.arid'
106
+
107
+ @classmethod
108
+ def seek(cls, realdir):
109
+ path = Path.seek(realdir, cls.projectaridname)
110
+ if path is None:
111
+ raise ProjectInfoNotFoundException(realdir)
112
+ return cls(path.parent, path)
113
+
114
+ @classmethod
115
+ def seekany(cls, realdir):
116
+ try:
117
+ return cls.seek(realdir)
118
+ except ProjectInfoNotFoundException:
119
+ pass
120
+ setuppath = Path.seek(realdir, 'setup.py')
121
+ if setuppath is not None:
122
+ log.info('Use setuptools mode.')
123
+ return setuptoolsinfo(setuppath)
124
+ log.info('Use uninstallable mode.')
125
+ projectdir = os.path.dirname(Path.seek(realdir, '.git'))
126
+ with openresource(__name__, 'setuptools.arid') as f:
127
+ info = cls(projectdir, f)
128
+ info.config.name = os.path.basename(os.path.abspath(projectdir))
129
+ return info
130
+
131
+ def __init__(self, projectdir, infopathorstream):
132
+ cc = ConfigCtrl()
133
+ Resource(__name__, 'projectinfo.arid', 'utf-8').source(cc.scope(), Entry([]))
134
+ cc.load(infopathorstream)
135
+ self.allbuildrequires = list(cc.r.build.requires)
136
+ self.allrequires = list(cc.r.requires)
137
+ self.config = cc.node
138
+ self.projectdir = projectdir
139
+
140
+ def mitpath(self):
141
+ return os.path.join(self.projectdir, self.config.MIT.path)
142
+
143
+ def contextworkspace(self):
144
+ return os.path.join(self.projectdir, '..')
145
+
146
+ def parsedrequires(self):
147
+ return Req.parselines(self.allrequires)
148
+
149
+ def localrequires(self):
150
+ return [r.namepart for r in self.parsedrequires() if r.isproject(self)]
151
+
152
+ def nextversion(self): # XXX: Deduce from tags instead?
153
+ import urllib.request, urllib.error, re, xml.dom.minidom as dom
154
+ pattern = re.compile('-([0-9]+)[-.]')
155
+ try:
156
+ with urllib.request.urlopen("https://pypi.org/simple/%s/" % self.config.name) as f:
157
+ doc = dom.parseString(subprocess.check_output(['tidy', '-asxml'], input = f.read()))
158
+ last = max(int(pattern.search(textcontent(a)).group(1)) for a in doc.getElementsByTagName('a'))
159
+ except urllib.error.HTTPError as e:
160
+ if 404 != e.code:
161
+ raise
162
+ last = 0
163
+ return str(max(10, last + 1))
164
+
165
+ def descriptionandurl(self):
166
+ import urllib.error, urllib.request, json, time
167
+ urlpath = "%s/%s" % (self.config.github.account, self.config.name)
168
+ while True:
169
+ try:
170
+ with urllib.request.urlopen("https://api.github.com/repos/%s" % urlpath) as f:
171
+ return json.loads(f.read().decode())['description'], "https://github.com/%s" % urlpath
172
+ except urllib.error.HTTPError as e:
173
+ if 403 != e.code:
174
+ raise
175
+ log.info("Sleep 1 minute due to: %s", e)
176
+ time.sleep(60)
177
+
178
+ def py_modules(self):
179
+ suffix = '.py'
180
+ return [name[:-len(suffix)] for name in os.listdir(self.projectdir) if name.endswith(suffix) and 'setup.py' != name and not name.startswith('test_')]
181
+
182
+ def mainmodules(self):
183
+ paths = list(Files.relpaths(self.projectdir, [mainmodules.extension], []))
184
+ with TemporaryDirectory() as tempdir:
185
+ scriptpath = os.path.join(tempdir, 'mainmodules.py')
186
+ with open(scriptpath, 'w') as f:
187
+ f.write(getsource(mainmodules))
188
+ with open(os.path.join(tempdir, 'venvpool.py'), 'w') as f:
189
+ f.write(getsource(venvpool))
190
+ for line in subprocess.check_output(["python%s" % next(iter(self.config.pyversions)), scriptpath, self.projectdir] + paths).splitlines():
191
+ yield MainModule(eval(line))
192
+
193
+ def console_scripts(self):
194
+ return [mm.console_script for mm in self.mainmodules()]
195
+
196
+ def devversion(self):
197
+ releases = [int(t[1:]) for t in subprocess.check_output(['git', 'tag'], cwd = self.projectdir, universal_newlines = True).splitlines() if 'v' == t[0]]
198
+ return "%s.dev0" % ((max(releases) if releases else 0) + 1)
199
+
200
+ class MainModule:
201
+
202
+ def __init__(self, d):
203
+ for k, v in d.items():
204
+ setattr(self, k, v)
205
+
206
+ def setuptoolsinfo(setuppath):
207
+ with openresource(__name__, 'setuptools.arid') as f:
208
+ info = ProjectInfo(os.path.dirname(setuppath), f)
209
+ setupkwargs = getsetupkwargs(setuppath, ['name', 'install_requires', 'entry_points'])
210
+ if 'name' in setupkwargs:
211
+ info.config.name = setupkwargs['name']
212
+ info.allrequires.extend(setupkwargs.get('install_requires', []))
213
+ console_scripts = setupkwargs.get('entry_points', {}).get('console_scripts')
214
+ info.console_scripts = lambda: console_scripts
215
+ return info
@@ -0,0 +1,2 @@
1
+ [build-system]
2
+ requires = [$join($map($(build_requires) it $"$(it)) $.(, ))]
pyven/release.arid ADDED
@@ -0,0 +1,7 @@
1
+ account = $(void)
2
+ cli
3
+ path = $(void)
4
+ upload = $(void)
5
+ path = $(cli path)
6
+ token = $gpg$(token_gpg $(account))
7
+ upload = $(cli upload)
pyven/release.py ADDED
@@ -0,0 +1,170 @@
1
+ 'Release project to PyPI, with manylinux wheels as needed.'
2
+ from .checks import EveryVersion
3
+ from .pipify import InstallDeps, pipify
4
+ from .projectinfo import ProjectInfo, SimpleInstallDeps
5
+ from .sourceinfo import SourceInfo
6
+ from .util import bgcontainer
7
+ from argparse import ArgumentParser
8
+ from aridity.config import ConfigCtrl
9
+ from diapyr.util import singleton
10
+ from itertools import chain
11
+ from lagoon.program import partial, Program
12
+ from pkg_resources import resource_filename
13
+ from tempfile import NamedTemporaryFile
14
+ from venvpool import dotpy, initlogging, Pip, Pool, TemporaryDirectory
15
+ import lagoon, logging, os, re, shutil, sys, sysconfig
16
+
17
+ log = logging.getLogger(__name__)
18
+ distrelpath = 'dist'
19
+ targetremote = 'origin'
20
+
21
+ class Arch:
22
+
23
+ def __init__(self, entrypointornone):
24
+ self.entrypoint = [] if entrypointornone is None else [entrypointornone]
25
+
26
+ def _images():
27
+ archlookup = dict(
28
+ i686 = Arch('linux32'),
29
+ x86_64 = Arch(None),
30
+ )
31
+ archmatch = re.compile("_(%s)$" % '|'.join(map(re.escape, archlookup))).search
32
+ images = {
33
+ 'manylinux_2_34_x86_64': '2024-11-23-da4547b',
34
+ 'manylinux_2_28_x86_64': '2024-11-30-fa0d298',
35
+ 'manylinux2014_x86_64': '2024-11-24-a3012f3',
36
+ 'manylinux2014_i686': '2024-11-23-da4547b',
37
+ }
38
+ for plat, imagetag in images.items():
39
+ yield Image(imagetag, plat, archlookup[archmatch(plat).group(1)])
40
+
41
+ class Image:
42
+
43
+ prefix = 'quay.io/pypa/'
44
+
45
+ @singleton
46
+ def pythonexe():
47
+ impl = "cp%s" % sysconfig.get_config_var('py_version_nodot')
48
+ return "/opt/python/%s-%s%s/bin/python" % (impl, impl, sys.abiflags)
49
+
50
+ def __init__(self, imagetag, plat, arch):
51
+ self.imagetag = imagetag
52
+ self.plat = plat
53
+ self.arch = arch
54
+
55
+ def makewheels(self, info): # TODO: This code would benefit from modern syntax.
56
+ from lagoon import docker
57
+ from lagoon.program import NOEOL
58
+ docker_print = docker[partial](stdout = None)
59
+ log.info("Make wheels for platform: %s", self.plat)
60
+ scripts = list(info.config.devel.scripts)
61
+ packages = list(info.config.devel.packages)
62
+ # TODO: Copy not mount so we can run containers in parallel.
63
+ with bgcontainer('-v', "%s:/io" % info.projectdir, "%s%s:%s" % (self.prefix, self.plat, self.imagetag)) as container:
64
+ def run(execargs, command):
65
+ docker_print(*chain(['exec'], execargs, [container], self.arch.entrypoint, command))
66
+ if packages:
67
+ run([], chain(['yum', 'install', '-y'], packages))
68
+ for script in scripts:
69
+ # TODO LATER: Run as ordinary sudo-capable user.
70
+ dirpath = docker[NOEOL]('exec', container, 'mktemp', '-d') # No need to cleanup, will die with container.
71
+ log.debug("In container dir %s run script: %s", dirpath, script)
72
+ run(['-w', dirpath, '-t'], ['sh', '-c', script])
73
+ docker_print.cp(resource_filename(__name__, 'patchpolicy.py'), "%s:/patchpolicy.py" % container)
74
+ run([], [self.pythonexe, '/patchpolicy.py'])
75
+ docker_print.cp(resource_filename(__name__, 'bdist.py'), "%s:/bdist.py" % container)
76
+ run(['-u', "%s:%s" % (os.geteuid(), os.getegid()), '-w', '/io'], chain([self.pythonexe, '/bdist.py', '--plat', self.plat], info.config.pyversions))
77
+
78
+ def main():
79
+ initlogging()
80
+ config = ConfigCtrl().loadappconfig(main, 'release.arid')
81
+ parser = ArgumentParser()
82
+ parser.add_argument('--upload', action = 'store_true')
83
+ parser.add_argument('path', nargs = '?', default = '.')
84
+ parser.parse_args(namespace = config.cli)
85
+ # XXX: Load info config to a scope in our config?
86
+ info = ProjectInfo.seek(config.path)
87
+ config.account = info.config.pypi.account
88
+ git = lagoon.git[partial](cwd = info.projectdir)
89
+ if git.status.__porcelain():
90
+ raise Exception('Uncommitted changes!')
91
+ log.debug('No uncommitted changes.')
92
+ remotename, _ = git.rev_parse.__abbrev_ref('@{u}').split('/')
93
+ if targetremote != remotename:
94
+ raise Exception("Current branch must track some %s branch." % targetremote)
95
+ log.debug("Good remote: %s", remotename)
96
+ with TemporaryDirectory() as tempdir:
97
+ copydir = os.path.join(tempdir, os.path.basename(os.path.abspath(info.projectdir)))
98
+ log.info("Copying project to: %s", copydir)
99
+ shutil.copytree(info.projectdir, copydir)
100
+ for relpath in release(config, git, ProjectInfo.seek(copydir)):
101
+ log.info("Replace artifact: %s", relpath)
102
+ destpath = os.path.join(info.projectdir, relpath)
103
+ try:
104
+ os.makedirs(os.path.dirname(destpath))
105
+ except OSError:
106
+ pass
107
+ shutil.copy2(os.path.join(copydir, relpath), destpath)
108
+
109
+ def uploadableartifacts(artifactrelpaths):
110
+ def acceptplatform(platform):
111
+ return 'any' == platform or platform.startswith('manylinux')
112
+ platformmatch = re.compile('-([^-]+)[.]whl$').search
113
+ for p in artifactrelpaths:
114
+ name = os.path.basename(p)
115
+ if not name.endswith('.whl') or acceptplatform(platformmatch(name).group(1)):
116
+ yield p
117
+ else:
118
+ log.debug("Not uploadable: %s", p)
119
+
120
+ def _warmups(info):
121
+ warmups = [w.split(':') for w in info.config.warmups]
122
+ if warmups:
123
+ # XXX: Use the same transient venv as used for running tests?
124
+ with InstallDeps(info, False, None) as installdeps, Pool(next(iter(info.config.pyversions))).readonlyortransient[True](installdeps) as venv:
125
+ for m, f in warmups:
126
+ with NamedTemporaryFile('w', suffix = dotpy, dir = info.projectdir) as script:
127
+ script.write("from %s import %s\n%s()" % (m, f.split('.')[0], f))
128
+ script.flush()
129
+ venv.run('check_call', ['.'] + installdeps.localreqs, os.path.basename(script.name)[:-len(dotpy)], [], cwd = info.projectdir)
130
+
131
+ def _runsetup(info, commands):
132
+ with Pool(next(iter(info.config.pyversions))).readonly(SimpleInstallDeps(info.allbuildrequires)) as venv: # TODO: Newer setuptools for PEP 625.
133
+ venv.run('check_call', ['.'], 'setup', commands, cwd = info.projectdir) # XXX: Should venvpool automatically include current dir?
134
+
135
+ def release(config, srcgit, info):
136
+ scrub = lagoon.git.clean._xdi[partial](cwd = info.projectdir, input = 'c', stdout = None)
137
+ scrub()
138
+ version = info.nextversion()
139
+ pipify(info, version)
140
+ EveryVersion(info, False, False, [], False, True).allchecks()
141
+ scrub()
142
+ for dirpath, dirnames, filenames in os.walk(info.projectdir):
143
+ for name in chain(filenames, dirnames):
144
+ if name.startswith('test_'): # TODO LATER: Allow project to add globs to exclude.
145
+ path = os.path.join(dirpath, name)
146
+ log.debug("Delete: %s", path)
147
+ (os.remove if name.endswith('.py') else shutil.rmtree)(path)
148
+ _warmups(info)
149
+ pipify(info, version)
150
+ shutil.rmtree(os.path.join(info.projectdir, '.git'))
151
+ setupcommands = []
152
+ if SourceInfo(info.projectdir).extpaths:
153
+ for image in _images():
154
+ image.makewheels(info)
155
+ else:
156
+ setupcommands.append('bdist_wheel')
157
+ _runsetup(info, setupcommands + ['sdist'])
158
+ artifactrelpaths = [os.path.join(distrelpath, name) for name in sorted(os.listdir(os.path.join(info.projectdir, distrelpath)))]
159
+ if config.upload:
160
+ srcgit.tag("v%s" % version, stdout = None)
161
+ # TODO LATER: If tag succeeded but push fails, we're left with a bogus tag.
162
+ srcgit.push.__tags(stdout = None) # XXX: Also update other remotes?
163
+ with config.token as token:
164
+ Program.text(sys.executable)._m.twine.upload('-u', '__token__', '-p', token, *uploadableartifacts(artifactrelpaths), cwd = info.projectdir, stdout = None, env = Pip.envpatch)
165
+ else:
166
+ log.warning("Upload skipped, use --upload to upload: %s", ' '.join(uploadableartifacts(artifactrelpaths)))
167
+ return artifactrelpaths
168
+
169
+ if '__main__' == __name__:
170
+ main()
pyven/setup.cfg.aridt ADDED
@@ -0,0 +1,2 @@
1
+ [bdist_wheel]
2
+ universal=$(universal)
pyven/setup.py.aridt ADDED
@@ -0,0 +1,23 @@
1
+ from setuptools import setup
2
+
3
+ def long_description():
4
+ with open('README.md') as f:
5
+ return f.read()
6
+
7
+ $readfile$./(sourceinfo.py)
8
+ sourceinfo = SourceInfo('.')
9
+ setup(
10
+ name = $"$(name),
11
+ version = $"$(version),
12
+ description = $"$(tagline),
13
+ long_description = $(long_description),
14
+ long_description_content_type = 'text/markdown',
15
+ url = $"$(url),
16
+ author = $"$(author),
17
+ author_email = $"$(author_email),
18
+ py_modules = [$join($map($(py_modules) $"$()) $.(, ))],
19
+ install_requires = [$join($map($(install_requires) $"$()) $.(, ))],
20
+ package_data = {'': [$join($map($(resource types) $"(*.$())) $.(, ))]},
21
+ entry_points = {'console_scripts': [$join($map($(console_scripts) $"$()) $.(, ))]},
22
+ **sourceinfo.setup_kwargs(),
23
+ )
pyven/setuptools.arid ADDED
@@ -0,0 +1,2 @@
1
+ licheck enabled = false
2
+ pyversions += 3
pyven/sourceinfo.py ADDED
@@ -0,0 +1,36 @@
1
+ class SourceInfo:
2
+
3
+ class PYXPath:
4
+
5
+ def __init__(self, module, path):
6
+ self.module = module
7
+ self.path = path
8
+
9
+ def make_ext(self):
10
+ g = {}
11
+ with open("%sbld" % self.path) as f: # Assume project root.
12
+ exec(f.read(), g)
13
+ return g['make_ext'](self.module, self.path)
14
+
15
+ def __init__(self, rootdir):
16
+ def addextpaths(dirpath, moduleprefix, suffix = '.pyx'):
17
+ for name in sorted(os.listdir(os.path.join(rootdir, dirpath))):
18
+ if name.endswith(suffix):
19
+ module = "%s%s" % (moduleprefix, name[:-len(suffix)])
20
+ if module not in extpaths:
21
+ extpaths[module] = self.PYXPath(module, os.path.join(dirpath, name))
22
+ from setuptools import find_packages
23
+ import os
24
+ self.packages = find_packages(rootdir)
25
+ extpaths = {}
26
+ addextpaths('.', '')
27
+ for package in self.packages:
28
+ addextpaths(package.replace('.', os.sep), "%s." % package)
29
+ self.extpaths = extpaths.values()
30
+
31
+ def setup_kwargs(self):
32
+ kwargs = dict(packages = self.packages)
33
+ if self.extpaths:
34
+ from Cython.Build import cythonize
35
+ kwargs['ext_modules'] = cythonize([path.make_ext() for path in self.extpaths])
36
+ return kwargs
pyven/tasks.py ADDED
@@ -0,0 +1,19 @@
1
+ 'Show all XX''X/TO''DO/FIX''ME comments in project.'
2
+ from .files import Files
3
+ from argparse import ArgumentParser
4
+ import subprocess
5
+
6
+ def main():
7
+ parser = ArgumentParser()
8
+ parser.add_argument('-q', action = 'count', default = 0)
9
+ config = parser.parse_args()
10
+ root, = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).decode().splitlines()
11
+ agcommand = ['ag', '--noheading', '--nobreak']
12
+ # XXX: Integrate with declared project resource types?
13
+ paths = list(Files.relpaths(root, ['.py', '.pyx', '.h', '.cpp', '.ui', '.java', '.kt', '.c', '.s', '.sh', '.arid', '.aridt', '.gradle', '.java', '.mk', '.js'], ['Dockerfile', 'Makefile']))
14
+ for tag in ['XX''X', 'TO''DO', 'FIX''ME'][config.q:]:
15
+ subprocess.call(agcommand + [tag + ' LATER'] + paths, cwd = root)
16
+ subprocess.call(agcommand + [tag + '(?! LATER)'] + paths, cwd = root)
17
+
18
+ if '__main__' == __name__:
19
+ main()