forked from cannatag/ldap3
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-binary.py
More file actions
Latest commit
394 lines (339 loc) · 15 KB
/
Copy pathsetup-binary.py
File metadata and controls
394 lines (339 loc) · 15 KB
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
391
392
393
394
"""
"""
# Created on 2018.06.12
#
# Author: Pedro Algarvio
#
# Copyright 2018 Giovanni Cannata
# Copyright 2018 Pedro Algarvio
#
# This file is part of ldap3.
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.
# Import python libs
importos
importsys
importjson
importglob
importshutil
importsubprocess
importmultiprocessing
importdistutils.dist
# pylint: disable=no-name-in-module
fromdistutils.coreimportCommand
fromdistutils.command.cleanimportclean
fromdistutils.command.build_pyimportbuild_py
fromdistutils.command.build_extimportbuild_ext
fromdistutils.command.installimportinstall
fromsetuptoolsimportsetup
fromsetuptools.command.developimportdevelop
# ----- Global Variables -------------------------------------------------------------------------------------------->
NO_EXTENSIONS_PLACEHOLDER=object()
version_dict=json.load(open('_version.json', 'r'))
version=str(version_dict['version'])
author=str(version_dict['author'])
email=str(version_dict['email'])
license=str(version_dict['license'])
url=str(version_dict['url'])
description=str(version_dict['description'])
package_name=str(version_dict['package_name']) +'-binary'
status=str(version_dict['status'])
# Change to pack source's directory prior to running any command
try:
SETUP_DIRNAME=os.path.dirname(__file__)
exceptNameError:
# We're most likely being frozen and __file__ triggered this NameError
# Let's work around that
SETUP_DIRNAME=os.path.dirname(sys.argv[0])
ifSETUP_DIRNAME!='':
os.chdir(SETUP_DIRNAME)
SETUP_DIRNAME=os.path.abspath(SETUP_DIRNAME)
# <---- Global Variables ---------------------------------------------------------------------------------------------
# ----- Custom Distutils/Setuptools Commands ------------------------------------------------------------------------>
classBuildPy(build_py):
deffind_package_modules(self, package, package_dir):
modules=build_py.find_package_modules(self, package, package_dir)
forpackage, module, filenameinmodules:
ifself.distribution.develop_modeisFalseandpackage=='ldap3.utils'andmodulein ('asn1', 'conv'):
# We have issues when cython compiling asn1, include it as a python module
yieldpackage, module, filename
continue
ifself.distribution.develop_modeisFalseandmodulenotin ('__init__',):
# We only want __init__ and _version python files
# All others will be built as extensions
continue
yieldpackage, module, filename
classBuildExt(build_ext):
defrun(self):
self.extensions=self.distribution.get_ext_modules()
build_ext.run(self)
defbuild_extensions(self):
ifint(self.distribution.concurrency) >1:
self.check_extensions_list(self.extensions)
importmultiprocessing.pool
multiprocessing.pool.ThreadPool(
processes=int(self.distribution.concurrency)).map(
self.build_extension, self.extensions)
else:
build_ext.build_extensions(self)
classClean(clean):
deffinalize_options(self):
self.distribution._ext_modules=None
clean.finalize_options(self)
defrun(self):
clean.run(self)
forsubdirin ('ldap3', 'tests'):
root=os.path.join(os.path.dirname(__file__), subdir)
fordirname, dirs, _inos.walk(root):
forto_remove_filenameinglob.glob('{0}/*.py[ocx]'.format(dirname)):
os.remove(to_remove_filename)
forto_remove_filenameinglob.glob('{0}/*.c'.format(dirname)):
os.remove(to_remove_filename)
forto_remove_filenameinglob.glob('{0}/*.so'.format(dirname)):
os.remove(to_remove_filename)
fordir_indirs:
ifdir_=='__pycache__':
shutil.rmtree(os.path.join(dirname, dir_))
classDevelop(develop):
deffinalize_options(self):
self.distribution.develop_mode=True
develop.finalize_options(self)
defrun(self):
# Clean up any previously generated cython files
self.run_command('clean')
develop.run(self)
classInstall(install):
deffinalize_options(self):
install.finalize_options(self)
ifself.distribution.has_ext_modules():
self.install_lib=self.install_platlib
defrun(self):
self.run_command('build_ext')
install.run(self)
classBuildWheels(Command):
description='Build manylinux1 wheel packages'
user_options= []
definitialize_options(self):
'''
Abstract method that is required to be overwritten
'''
deffinalize_options(self):
'''
Abstract method that is required to be overwritten
'''
defrun(self):
try:
docker_binary=subprocess.check_output('which docker', shell=True).decode(sys.stdin.encodingor'asccii').strip()
exceptsubprocess.CalledProcessError:
print('Docker binary not found')
sys.exit(1)
formanylinux_docker_imagein ('quay.io/pypa/manylinux1_x86_64',
'quay.io/pypa/manylinux1_i686'):
ifmanylinux_docker_image.endswith('i686'):
pre_cmd='linux32'
else:
pre_cmd=''
dest=manylinux_docker_image.replace('quay.io/pypa/manylinux1_', '')
try:
subprocess.check_call('{} pull {}'.format(docker_binary, manylinux_docker_image), shell=True)
exceptsubprocess.CalledProcessErrorasexc:
print('Failed to download docker image {}: {}'.format(manylinux_docker_image, exc))
sys.exit(1)
try:
subprocess.check_call(
'{docker_binary} run --rm -v `pwd`:/io {docker_image} {pre_cmd} '
'/io/build-binary-wheels.sh {dest} `id -u` `id -g`'.format(
docker_binary=docker_binary,
docker_image=manylinux_docker_image,
pre_cmd=pre_cmd,
dest=dest
),
shell=True
)
exceptsubprocess.CalledProcessErrorasexc:
print('Failed to build package with docker image {}: {}'.format(manylinux_docker_image, exc))
sys.exit(1)
try:
packages_listing=subprocess.check_output('ls wheelhouse/', shell=True).decode(sys.stdin.encodingor'asccii')
print('Built Packages')
print(packages_listing)
exceptsubprocess.CalledProcessErrorasexc:
print('Failed to list built packages: {}'.format(exc))
sys.exit(1)
# <---- Custom Distutils/Setuptools Commands -------------------------------------------------------------------------
# ----- Custom Distribution Class ----------------------------------------------------------------------------------->
classDistribution(distutils.dist.Distribution):
'''
Distribution class
'''
global_options=distutils.dist.Distribution.global_options+ [
('concurrency=', None, 'Parallelize extension module builds')
]
def__init__(self, attrs=None):
distutils.dist.Distribution.__init__(self, attrs)
self._ext_modules=NO_EXTENSIONS_PLACEHOLDER
self.concurrency=multiprocessing.cpu_count()
self.develop_mode=False
self.name=package_name
self.version=version
self.description=description
self.author=author
self.author_email=email
self.url=url
self.cmdclass.update(
{
'clean': Clean,
'build_py': BuildPy,
'build_ext': BuildExt,
'install': Install,
'build_wheels': BuildWheels,
'develop': Develop,
}
)
self.license=license
self.packages, self.package_dir, self.package_data=self.discover_packages()
self.zip_safe=False
self.update_metadata()
defupdate_metadata(self):
forattrnameindir(self):
ifattrname.startswith('__'):
continue
ifattrname=='ext_modules':
# Don't trigger cythonize
continue
attrvalue=getattr(self, attrname, None)
ifattrvalue==0:
continue
ifhasattr(self.metadata, 'set_{0}'.format(attrname)):
getattr(self.metadata, 'set_{0}'.format(attrname))(attrvalue)
elifhasattr(self.metadata, attrname):
try:
setattr(self.metadata, attrname, attrvalue)
exceptAttributeError:
pass
deffind_ext(self):
fromCython.Distutils.extensionimportExtension
ret= []
forpackagein ('ldap3',):
forroot, _, filesinos.walk(os.path.join(SETUP_DIRNAME, package)):
commonprefix=os.path.commonprefix([SETUP_DIRNAME, root])
forfilenameinfiles:
full=os.path.join(root, filename)
ifnotfilename.endswith(('.py', '.c')):
continue
iffilenamein ('__init__.py',):
continue
relpath=os.path.join(root, filename).split(commonprefix)[-1][1:]
ifrelpathin ('ldap3/utils/asn1.py', 'ldap3/utils/conv.py'):
# We have issues when cython compiling asn1, skipt it
continue
module=os.path.splitext(relpath)[0].replace(os.sep, '.')
ret.append(Extension(module, [full]))
returnret
defdiscover_packages(self):
modules= []
pkg_data= {}
pkg_dir= {}
forpackagein ('ldap3',):
forroot, _, filesinos.walk(os.path.join(SETUP_DIRNAME, package)):
if'__init__.py'notinfiles:
continue
pdir=os.path.relpath(root, SETUP_DIRNAME)
modname=pdir.replace(os.sep, '.')
modules.append(modname)
pkg_data.setdefault(modname, []).append('*.so')
pkg_dir[modname] =pdir
returnmodules, pkg_dir, pkg_data
defget_ext_modules(self):
ifself.develop_modeisFalseandself._ext_modulesisNO_EXTENSIONS_PLACEHOLDER:
fromCython.Buildimportcythonize
self.ext_modules=self._ext_modules=cythonize(self.find_ext(),
nthreads=int(self.concurrency))
returnself._ext_modules
# ----- Static Data -------------------------------------------------------------------------------------------->
@property
def_property_classifiers(self):
return [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP'
]
#@property
#def _property_dependency_links(self):
# return []
#@property
#def _property_tests_require(self):
# return ['pytest']
# <---- Static Data ----------------------------------------------------------------------------------------------
# ----- Dynamic Data -------------------------------------------------------------------------------------------->
@property
def_property_package_data(self):
returnself.package_data
@property
def_property_data_files(self):
return []
@property
def_property_install_requires(self):
requirements= [i.strip() foriinopen('requirements.txt').readlines()]
# Uncomment when pyasn1-binary is also a thing
#for idx, requirement in enumerate(requirements):
# if requirement.startswith('pyasn1'):
# _, req_version = requirement.split('pyasn1', 1)
# requirements[idx] = 'pyasn1-binary' + req_version
returnrequirements
@property
def_property_extras_require(self):
return {}
@property
def_property_scripts(self):
return []
@property
def_property_setup_requires(self):
return []
#@property
#def _property_entry_points(self):
# return {'console_scripts': ['....']}
# <---- Dynamic Data ---------------------------------------------------------------------------------------------
# ----- Overridden Methods -------------------------------------------------------------------------------------->
defparse_command_line(self):
args=distutils.dist.Distribution.parse_command_line(self)
# Setup our property functions after class initialization and
# after parsing the command line since most are set to None
# ATTENTION: This should be the last step before returning the args or
# some of the requirements won't be correctly set
forfuncnameindir(self):
ifnotfuncname.startswith('_property_'):
continue
property_name=funcname.split('_property_', 1)[-1]
setattr(self, property_name, getattr(self, funcname))
returnargs
defhas_ext_modules(self):
# Make sure we tell distutils that this is not a pure python package
returnself.develop_modeisFalse
defhas_pure_modules(self):
# Make sure we tell distutils that this is a pure python package
returnTrue
# <---- Overridden Methods ---------------------------------------------------------------------------------------
# <---- Custom Distribution Class ------------------------------------------------------------------------------------
if__name__=='__main__':
setup(distclass=Distribution)