-
Notifications
You must be signed in to change notification settings - Fork 3
/
setup.py
390 lines (353 loc) · 14.4 KB
/
setup.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
long_description = """\
The package *cypari* is a Python wrapper for the `PARI library
<http://pari.math.u-bordeaux.fr/>`_, a computer algebra system for
number theory computations. It is derived from the `corresponding
component
<https://github.com/sagemath/sage/blob/797dd7b4c273556d9677fadffa2ef6dd7f113857/src/sage/libs/cypari2/gen.pyx>`_
of `SageMath <http://www.sagemath.org>`_, but is independent of the rest of
SageMath and can be used with any recent version of Python 3.
"""
no_cython_message = """
Building CyPari requires Cython (>= 3.0.0) to be installed.
"""
import sys
if sys.version_info < (3,5):
print("Python 3.6 or higher is required")
sys.exit()
if not sys.maxsize > 2**32:
raise RuntimeError('32 bit systems are no longer supported.')
import os
import re
import sysconfig
import subprocess
import shutil
import site
import platform
import time
from glob import glob
from setuptools import setup, Command
from distutils.extension import Extension
from distutils.command.build_ext import build_ext
from distutils.command.sdist import sdist
from distutils.util import get_platform
from subprocess import Popen, PIPE
if sys.platform == 'win32':
# We expect to be using:
# * Windows Visual Studio 2022 with the Universal C Runtime and the
# Windows 11 SDK 10.0.22000.0 installed.
# * An Msys-2 with the UCRT64 environment installed for gcc 13.2.0
ext_compiler = 'msvc'
MSVC_extra_objects = [
r'C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\um\x64\Uuid.lib',
r'C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\um\x64\kernel32.lib',
r'C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\ucrt\x64\ucrt.lib',
r'C:\msys64\ucrt64\lib\gcc\x86_64-w64-mingw32\14.2.0\libgcc.a'
]
else:
ext_compiler = ''
# Path setup for building with the mingw C compiler on Windows.
if sys.platform == 'win32' and not os.path.exists('libcache/pari'):
# We always build the Pari library with mingw, no matter which compiler
# is used for the CyPari extension.
# Make sure that our C compiler matches our python and that we can run bash
# and other needed utilities such as find.
bash_proc = Popen(['bash', '-c', 'echo $PATH'], stdout=PIPE, stderr=PIPE)
BASHPATH, _ = bash_proc.communicate()
BASHPATH = BASHPATH.decode('utf8')
BASH = r'C:\msys64\usr\bin\bash'
else:
BASHPATH = os.environ['PATH']
BASH = '/bin/bash'
PARIDIR = 'pari'
GMPDIR = 'gmp'
pari_include_dir = os.path.join('libcache', PARIDIR, 'include')
pari_library_dir = os.path.join('libcache', PARIDIR, 'lib')
pari_static_library = os.path.join(pari_library_dir, 'libpari.a')
gmp_library_dir = os.path.join('libcache', GMPDIR, 'lib')
gmp_static_library = os.path.join(gmp_library_dir, 'libgmp.a')
MSVC_include_dirs = [
r'C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\um',
r'C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\ucrt',
r'C:\Program Files (x86)\Windows Kits\10\Include\10.0.22000.0\shared'
]
class CyPariClean(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
junkdirs = (glob('build/lib*') +
glob('build/bdist*') +
glob('build/temp*') +
glob('cypari*.egg-info')
)
for dir in junkdirs:
try:
shutil.rmtree(dir)
except OSError:
pass
junkfiles = (glob('cypari/*.so*') +
glob('cypari/*.pyc') +
glob('cypari/_pari.c') +
glob('cypari/_pari*.h') +
glob('cypari/auto*.pxi') +
glob('cypari/auto*.pxd') +
glob('cypari/*.tmp')
)
for file in junkfiles:
try:
os.remove(file)
except OSError:
pass
class CyPariTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
version_info = sys.version_info
if int(version_info[1]) < 11:
build_lib_dir = os.path.join(
'build',
'lib.{platform}-{version_info[0]}.{version_info[1]}'.format(
platform=sysconfig.get_platform(),
version_info=sys.version_info)
)
else:
build_lib_dir = os.path.join(
'build',
'lib.{platform}-cpython-{version_info[0]}{version_info[1]}'.format(
platform=sysconfig.get_platform(),
version_info=sys.version_info)
)
print(build_lib_dir)
sys.path.insert(0, os.path.abspath(build_lib_dir))
from cypari.test import runtests
sys.exit(runtests())
def check_call(args):
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
executable = args[0]
command = [a for a in args if not a.startswith('-')][-1]
raise RuntimeError(command + ' failed for ' + executable)
def python_major(python):
proc = subprocess.Popen([python, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = proc.communicate()
# Python 2 writes to stderr, but Python 3 writes to stdout
return (output + errors).decode().split()[1].split('.')[0]
class CyPariRelease(Command):
user_options = [('install', 'i', 'install the release into each Python')]
def initialize_options(self):
self.install = False
def finalize_options(self):
pass
def run(self):
if os.path.exists('build'):
shutil.rmtree('build')
if os.path.exists('dist'):
shutil.rmtree('dist')
for filename in glob('cypari/_pari*.c'):
os.remove(filename)
pythons = os.environ.get('RELEASE_PYTHONS', sys.executable).split(',')
print('releasing for: %s'%(', '.join(pythons)))
for python in pythons:
check_call([python, 'setup.py', 'clean'])
check_call([python, 'setup.py', 'build'])
check_call([python, 'setup.py', 'test'])
# Save a copy of the _pari.c file for each major version of Python.
_pari_c_name = '_pari_py%s.c'%python_major(python)
_pari_c_path = os.path.join('cypari', _pari_c_name)
if not os.path.exists(_pari_c_path):
os.rename(os.path.join('cypari', '_pari.c'), _pari_c_path)
if sys.platform.startswith('linux'):
plat = get_platform().replace('linux', 'manylinux1')
plat = plat.replace('-', '_')
check_call([python, 'setup.py', 'bdist_wheel', '-p', plat])
check_call([python, 'setup.py', 'bdist_egg'])
else:
check_call([python, 'setup.py', 'bdist_wheel'])
if self.install:
check_call([python, 'setup.py', 'install'])
# Build sdist using the *first* specified Python
check_call([pythons[0], 'setup.py', 'sdist'])
# Double-check the Linux wheels
if sys.platform.startswith('linux'):
for name in os.listdir('dist'):
if name.endswith('.whl'):
subprocess.check_call(['auditwheel', 'repair',
os.path.join('dist', name)])
win64_py3_decls = b'''
'''
win64_py2_decls = b'''
'''
decls = b'''
'''
class CyPariBuildExt(build_ext):
def run(self):
building_sdist = False
if os.path.exists('pari_src'):
# We are building an sdist. Move the Pari source code into build.
if not os.path.exists('build'):
os.mkdir('build')
os.rename('pari_src', os.path.join('build', 'pari_src'))
os.rename('gmp_src', os.path.join('build', 'gmp_src'))
building_sdist = True
if (not os.path.exists(os.path.join('libcache', PARIDIR))
or not os.path.exists(os.path.join('libcache', GMPDIR))):
if sys.platform == 'win32':
# This is meant to work even in a Windows Command Prompt
cmd = r'export PATH="%s" ; export MSYSTEM=UCRT64 ; bash build_pari.sh'%BASHPATH
else:
cmd = r'export PATH="%s" ; bash build_pari.sh'%BASHPATH
if subprocess.call([BASH, '-c', cmd]):
sys.exit("***Failed to build PARI library***")
if building_sdist:
build_ext.run(self)
return
if (not os.path.exists(os.path.join('cypari', 'auto_gen.pxi')) or
not os.path.exists(os.path.join('cypari', 'auto_instance.pxi'))):
import autogen
autogen.rebuild()
# Provide declarations in an included .pxi file which indicate
# whether we are building for 64 bit Python on Windows, and
# which version of Python we are using. We need to handle 64
# bit Windows differently because (a) it is the only 64 bit
# system with 32 bit longs and (b) Pari deals with this by:
# #define long long long thereby breaking lots of stuff in the
# Python headers.
long_include = os.path.join('cypari', 'pari_long.pxi')
if sys.platform == 'win32':
if sys.version_info.major == 2:
include_file = os.path.join('cypari', 'long_win64py2.pxi')
else:
include_file = os.path.join('cypari', 'long_win64py3.pxi')
else:
include_file = os.path.join('cypari', 'long_generic.pxi')
with open(include_file, 'rb') as input:
code = input.read()
# Don't touch the long_include file unless it has changed, to avoid
# unnecessary compilation.
if os.path.exists(long_include):
with open(long_include, 'rb') as input:
old_code = input.read()
else:
old_code = b''
if old_code != code:
with open(long_include, 'wb') as output:
output.write(code)
# If we have Cython, check that .c files are up to date
# try:
# from Cython.Build import cythonize
# cythonize([os.path.join('cypari', '_pari.pyx')],
# compiler_directives={'language_level':2})
# except ImportError:
# if not os.path.exists(os.path.join('cypari', '_pari.c')):
# sys.exit(no_cython_message)
from Cython.Build import cythonize
_pari_pyx = os.path.join('cypari', '_pari.pyx')
_pari_c = os.path.join('cypari', '_pari.c')
cythonize([_pari_pyx],
compiler_directives={'language_level':2})
if sys.platform == 'win32':
# patch _pari.c to deal with #define long long long
with open('_pari.c', 'w') as outfile:
with open(_pari_c) as infile:
for line in infile.readlines():
if line.find('pycore') >= 0:
outfile.write(
' #undef long\n%s'
' #define long long long\n' %line)
else:
outfile.write(line)
os.unlink(_pari_c)
os.rename('_pari.c', _pari_c)
build_ext.run(self)
class CyPariSourceDist(sdist):
def _tarball_info(self, lib):
lib_re = re.compile(r'(%s-[0-9\.]+)\.tar\.[bg]z2*'%lib)
for f in os.listdir('.'):
lib_match = lib_re.search(f)
if lib_match:
break
return lib_match.group(), lib_match.groups()[0]
def run(self):
tarball, dir = self._tarball_info('pari')
check_call(['tar', 'xfz', tarball])
os.rename(dir, 'pari_src')
tarball, dir = self._tarball_info('gmp')
check_call(['tar', 'xfj', tarball])
os.rename(dir, 'gmp_src')
sdist.run(self)
shutil.rmtree('pari_src')
shutil.rmtree('gmp_src')
link_args = []
if sys.platform == 'darwin':
compile_args=['-mmacosx-version-min=10.9', '-Wno-unreachable-code',
'-Wno-unreachable-code-fallthrough']
elif sys.platform == 'win32':
# Ignore the assembly language inlines when building the extension.
compile_args = ['/DDISABLE_INLINE']
if False: # Toggle for debugging symbols
compile_args += ['/Zi']
link_args += ['/DEBUG']
# # Add the mingw crt objects needed by libpari.
link_args += [
os.path.join('Windows', 'crt', 'libparicrt64.a'),
'advapi32.lib',
'legacy_stdio_definitions.lib',
os.path.join('Windows', 'crt', 'get_output_format64.o')
]
else:
compile_args = []
link_args += [pari_static_library, gmp_static_library]
if sys.platform.startswith('linux'):
link_args += ['-Wl,-Bsymbolic-functions', '-Wl,-Bsymbolic']
include_dirs = [pari_include_dir]
extra_objects = []
if sys.platform == 'win32':
include_dirs += MSVC_include_dirs
extra_objects += MSVC_extra_objects
_pari = Extension(name='cypari._pari',
sources=['cypari/_pari.c'],
include_dirs=include_dirs,
extra_objects=extra_objects,
extra_link_args=link_args,
extra_compile_args=compile_args)
# Load the version number.
sys.path.insert(0, 'cypari')
from version import __version__
sys.path.pop(0)
setup(
name = 'cypari',
version = __version__,
description = "Sage's PARI extension, modified to stand alone.",
packages = ['cypari'],
package_dir = {'cypari':'cypari'},
cmdclass = {
'build_ext': CyPariBuildExt,
'clean': CyPariClean,
'test': CyPariTest,
'release': CyPariRelease,
'sdist': CyPariSourceDist,
},
ext_modules = [_pari],
zip_safe = False,
long_description = long_description,
url = 'https://bitbucket.org/t3m/cypari',
author = 'Marc Culler and Nathan M. Dunfield',
author_email = '[email protected], [email protected]',
license='GPLv2+',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Operating System :: OS Independent',
'Programming Language :: C',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Mathematics',
],
keywords = 'Pari, SageMath, SnapPy',
)