Debian Codegraph @

setup.py

raw symbols ◀ ▶ SCIP
3 Debian patches touch this file
1 import os
2 import re
3 import shutil
4 import subprocess
5 import sys
6 import warnings
7
8 import setuptools
9 import setuptools.command.build_ext
10 import wheel.bdist_wheel
11
•12 import pybind11
13
14 _this_dir = os.path.dirname(os.path.abspath(__file__))
15 _build_dir = os.path.join(_this_dir, 'build', 'python')
16
17 _cmake_file = os.path.join(_this_dir, 'CMakeLists.txt')
18 _author_file = os.path.join(_this_dir, 'AUTHORS')
19 _readme_file = os.path.join(_this_dir, 'README.md')
20 _fallback_version = '1.4.1'
21
22
23 def _get_version_from_git():
24 try:
25 raw = subprocess.check_output(
26 ['git', 'describe', '--tags', '--long', '--always'],
27 cwd=_this_dir,
28 stderr=subprocess.DEVNULL,
29 ).decode('utf-8').strip()
30 except (OSError, subprocess.CalledProcessError):
31 return ''
32
33 dirty = ''
34 for diff_cmd in (['git', 'diff', '--quiet'], ['git', 'diff', '--cached', '--quiet']):
35 try:
36 subprocess.check_call(
37 diff_cmd,
38 cwd=_this_dir,
39 stdout=subprocess.DEVNULL,
40 stderr=subprocess.DEVNULL,
41 )
42 except (OSError, subprocess.CalledProcessError):
43 dirty = '.dirty'
44 break
45
46 release_match = re.match(r'^(?:v|ver\.)(\d+\.\d+\.\d+)-0-g[0-9a-f]+$', raw)
47 if release_match:
48 return '{}{}'.format(release_match.group(1), dirty)
49
50 dev_match = re.match(r'^(?:v|ver\.)(\d+\.\d+\.\d+)-(\d+)-g([0-9a-f]+)$', raw)
51 if dev_match:
52 return '{}.dev{}+g{}{}'.format(
53 dev_match.group(1),
54 dev_match.group(2),
55 dev_match.group(3),
56 dirty,
57 )
58
59 return '{}+g{}{}'.format(_fallback_version, raw, dirty)
60
61
62 def get_version_info():
63 # Prefer Git-derived version from environment (set by CI or compute-version.sh)
64 env_version = os.environ.get('VERSION', '')
65 if env_version:
66 # Strip leading 'v' prefix for PEP 440 compatibility
67 return env_version.lstrip('v')
68
69 git_version = _get_version_from_git()
70 if git_version:
71 return git_version
72
73 return _fallback_version
74
75
76 def get_author_info():
77 if not os.path.isfile(_author_file):
78 return 'BYVoid', '[email protected]'
79
80 authors = []
81 emails = []
82 author_pattern = re.compile(r'(.+) <(.+)>')
83 with open(_author_file, 'rb') as f:
84 for line in f:
85 match = author_pattern.search(line.decode('utf-8'))
86 if not match:
87 continue
88 authors.append(match.group(1))
89 emails.append(match.group(2))
90
91 if len(authors) == 0:
92 return 'BYVoid', '[email protected]'
93
94 return ', '.join(authors), ', '.join(emails)
95
96
97 def get_long_description():
98 with open(_readme_file, 'rb') as f:
99 return f.read().decode('utf-8')
100
101
102 def build_libopencc(output_path):
•103 return
104 print('building libopencc into %s' % _build_dir)
105
106 is_windows = sys.platform == 'win32'
107
108 # Make build directories
109 os.makedirs(_build_dir, exist_ok=True)
110
111 # Configure
112 cmake_args = [
113 '-DBUILD_DOCUMENTATION:BOOL=OFF',
114 '-DBUILD_SHARED_LIBS:BOOL=OFF',
115 '-DENABLE_GTEST:BOOL=OFF',
116 '-DENABLE_BENCHMARK:BOOL=OFF',
117 '-DBUILD_OPENCC_JIEBA_PLUGIN:BOOL=OFF',
118 '-DBUILD_PYTHON:BOOL=ON',
119 '-DCMAKE_BUILD_TYPE=Release',
120 '-DCMAKE_INSTALL_PREFIX={}'.format(output_path),
121 '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={}'.format(output_path),
122 '-DPYTHON_EXECUTABLE={}'.format(sys.executable),
123 ]
124
125 if is_windows:
126 cmake_args += \
127 ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE={}'.format(output_path)]
128 if sys.maxsize > 2**32:
129 cmake_args += ['-A', 'x64']
130
131 cmd = ['cmake', '-B', _build_dir] + cmake_args
132 errno = subprocess.call(cmd)
133 assert errno == 0, 'Configure failed'
134
135 # Build
136 cmd = [
137 'cmake', '--build', _build_dir,
138 '--config', 'Release',
139 '--target', 'install'
140 ]
141 errno = subprocess.call(cmd)
142 assert errno == 0, 'Build failed'
143
144
145 class OpenCCExtension(setuptools.Extension, object):
146 def __init__(self, name, sourcedir=''):
147 setuptools.Extension.__init__(self, name, sources=[])
148 self.sourcedir = os.path.abspath(sourcedir)
149
150
151 class BuildExtCommand(setuptools.command.build_ext.build_ext, object):
152 def build_extension(self, ext):
•153 project_root = os.path.abspath(_this_dir)
154 build_dir = os.environ.get('OPENCC_BUILD_DIR', 'obj-x86_64-linux-gnu')
155 lib_path = os.path.join(project_root, build_dir, 'src')
156 ext.include_dirs.append(pybind11.get_include())
157 ext.include_dirs.append('src')
158 ext.library_dirs = [lib_path]
159 if isinstance(ext, OpenCCExtension):
160 build_libopencc(output_path)
161 else:
162 super(BuildExtCommand, self).build_extension(ext)
163
164
165 class BDistWheelCommand(wheel.bdist_wheel.bdist_wheel, object):
166 """Custom bdsit_wheel command that will change
167 default plat-name based on PEP 425 and PEP 513
168 """
169
170 @staticmethod
171 def _determine_platform_tag():
172 if sys.platform == 'win32':
173 if 'amd64' in sys.version.lower():
174 return 'win-amd64'
175 return sys.platform
176
177 if sys.platform == 'darwin':
178 _, _, _, _, machine = os.uname()
179 if machine == 'x86_64':
180 return 'macosx-10.9-{}'.format(machine)
181 if machine == 'arm64':
182 return 'macosx-11.0-{}'.format(machine)
183 else:
184 raise NotImplementedError
185
186 if os.name == 'posix':
187 _, _, _, _, machine = os.uname()
188 return 'manylinux2014-{}'.format(machine)
189
190 warnings.warn(
191 'Windows macos and linux are all not detected, '
192 'Proper distribution name cannot be determined.')
193 from distutils.util import get_platform
194 return get_platform()
195
196 def initialize_options(self):
197 super(BDistWheelCommand, self).initialize_options()
198 self.plat_name = self._determine_platform_tag()
199
200
201 packages = ['opencc', 'opencc.clib']
202
203 version_info = get_version_info()
204 author_info = get_author_info()
205
206 setup_requires = []
207 if not shutil.which('cmake'):
208 setup_requires.append('cmake')
209
210 setuptools.setup(
211 name='OpenCC',
212 version=version_info,
213 author=author_info[0],
214 author_email=author_info[1],
215 description=" Conversion between Traditional and Simplified Chinese",
216 long_description=get_long_description(),
217 long_description_content_type="text/markdown",
218 url="https://github.com/BYVoid/OpenCC",
219
220 packages=packages,
221 package_dir={'opencc': 'python/opencc'},
222 ext_modules=[
•223 setuptools.Extension(
224 'opencc.clib.opencc_clib',
225 sources=['src/py_opencc.cpp'],
226 libraries=['opencc'],
227 language='c++'
228 )
229 ],
230 cmdclass={
231 'build_ext': BuildExtCommand,
232 'bdist_wheel': BDistWheelCommand,
233 },
234 setup_requires=setup_requires,
235
236 classifiers=[
237 'Development Status :: 5 - Production/Stable',
238 'Intended Audience :: Developers',
239 'Intended Audience :: Science/Research',
240 'Natural Language :: Chinese (Simplified)',
241 'Natural Language :: Chinese (Traditional)',
242 'Programming Language :: Python',
243 'Programming Language :: Python :: 3',
244 'License :: OSI Approved :: Apache Software License',
245 'Topic :: Scientific/Engineering',
246 'Topic :: Software Development',
247 'Topic :: Software Development :: Libraries',
248 'Topic :: Software Development :: Libraries :: Python Modules',
249 'Topic :: Software Development :: Localization',
250 'Topic :: Text Processing :: Linguistic',
251 'Typing :: Typed',
252 ],
253 license='Apache License 2.0',
254 keywords=['opencc', 'convert', 'chinese'],
255 )