-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
482 lines (415 loc) · 16 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#!/usr/bin/env python3
import io
import os
import subprocess
import sys
from pathlib import Path
from typing import NoReturn, Union, Set, List
from setuptools import find_packages, setup, Command
# In that example author and maintainer is the same person.
NAME = 'action-demo'
DESCRIPTION = 'Actions Demo'
URL = 'https://github.com/dl1998/action-demo'
EMAIL = '[email protected]'
AUTHOR = 'Dmytro Leshchenko'
REQUIRES_PYTHON = '>=3.7.0'
VERSION = '1.1.7'
RELEASE = VERSION
here = os.path.abspath(os.path.dirname(__file__))
long_description = ''
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
except FileNotFoundError:
long_description = DESCRIPTION
about = {}
used_python = 'python'
try:
used_python = os.environ['USED_PYTHON']
except KeyError:
if 'prepare_venv' in sys.argv:
print('USED_PYTHON not found in environment variables, default python version will be used.')
if not VERSION:
project_slug = NAME.lower().replace("-", "_").replace(" ", "_")
with open(os.path.join(here, 'sources', project_slug, '__version__.py')) as file:
exec(file.read(), about)
else:
about['__version__'] = VERSION
def check_status_code(status_code, successful_message, error_message) -> NoReturn:
"""
Check status code and based on status code print one of two messages.
:raises CommandExecutionException: If status code different from 0.
:param status_code: Checked status code, returned by command.
:type status_code: int
:param successful_message: Message that will be printed, if status code equals to 0.
:type successful_message: str
:param error_message: Message that will be printed, if status code is different from 0.
:type error_message: str
"""
if status_code == 0:
print(successful_message)
else:
raise CommandExecutionException(error_message)
class UnknownOSException(Exception):
"""
Unknown operating system exception.
"""
pass
class CommandExecutionException(Exception):
"""
Exception that will be used, if error occurred in command execution.
"""
pass
class PrepareVirtualEnvironmentCommand(Command):
"""
Support setup.py create venv and install requirements.
"""
description = 'Create venv and install requirements from requirements.txt file.'
user_options = []
@staticmethod
def status(text: str) -> NoReturn:
"""
Method will be used for printing information to console.
:param text: Parameter that will be printed to console.
:type text: str
"""
print(text)
def initialize_options(self) -> NoReturn:
"""
If command receive arguments, then method can be used to set default values.
"""
pass
def finalize_options(self) -> NoReturn:
"""
If command receive arguments, then method can be used to set final values for arguments.
"""
pass
def __create_venv(self, venv_path: str) -> NoReturn:
"""
Create python virtual environment.
:raises CommandExecutionException: If error occurred during the command execution.
:param venv_path: Path to place where located virtual environment.
:type venv_path: str
"""
self.status('Create venv')
status_code = os.system(f'{used_python} -m venv {venv_path}')
successful_message = 'Venv successfully created'
error_message = 'Error occurred during venv creation, installation will not be executed'
check_status_code(status_code, successful_message, error_message)
def __install_requirements(self, venv_path: str) -> NoReturn:
"""
Install requirements from requirements.txt file.
:raises CommandExecutionException: If error occurred during the command execution.
:path venv_path: Virtual environment for which install requirements.
:type venv_path: str
"""
requirements_file_path = os.path.join(here, 'requirements.txt')
venv_pip = None
if sys.platform == 'linux':
venv_pip = os.path.join(venv_path, 'bin', 'pip3')
elif sys.platform == 'win32':
venv_pip = os.path.join(venv_path, 'Scripts', 'pip3')
else:
raise UnknownOSException(f'Unknown operation system: {sys.platform}.')
self.status('Check requirements.txt')
requirements_exists = os.path.exists(requirements_file_path)
if requirements_exists:
self.status('Install requirements from requirements.txt')
status_code = os.system(f'{venv_pip} install --upgrade --requirement requirements.txt')
successful_message = 'Installation completed successfully'
error_message = 'Error occurred during the installation'
check_status_code(status_code, successful_message, error_message)
else:
self.status('Requirements file not found')
def run(self) -> NoReturn:
"""
Create virtual environment and install all needed requirements.
"""
venv_path = os.path.join(here, 'venv')
try:
self.__create_venv(venv_path)
self.__install_requirements(venv_path)
except CommandExecutionException as execution_exception:
print(execution_exception)
except UnknownOSException as unknown_os_exception:
print(unknown_os_exception)
class BuildDocsCommand(Command):
"""
Custom command to build documentation with Sphinx
"""
doc_dir: Path
user_options = [
('doc-dir=', None, 'The documentation output directory'),
]
def initialize_options(self):
self.doc_dir = None
self.source_dir = None
self.output_dir = None
def finalize_options(self) -> None:
self.doc_dir = Path(self.doc_dir) if self.doc_dir else Path(__file__).parent.joinpath('docs')
if self.source_dir is None:
self.source_dir = self.doc_dir.joinpath('source')
if self.output_dir is None:
self.output_dir = self.doc_dir.joinpath('build')
def run(self):
build_command = [
'sphinx-build',
'-b', 'html',
'-d', str(self.doc_dir.joinpath('build/doctrees')),
'-j', 'auto',
str(self.source_dir),
str(self.output_dir)
]
try:
print(' '.join(build_command))
subprocess.check_call(build_command)
except subprocess.CalledProcessError as e:
print(f"Error: Failed to build documentation with Sphinx: {e}")
raise
class SphinxGenerate(Command):
"""
Class responsible for Sphinx project generation.
"""
name: str
author: str
version: str
release: str
language: str
template: str
doc_dir: str
user_options = [
('name', None, 'The project name'),
('author', None, 'The project author'),
('version', None, 'The project version'),
('release', None, 'The project release'),
('language', None, 'The project language'),
('template', None, 'The project template'),
('doc-dir', None, 'The project root'),
]
def initialize_options(self) -> NoReturn:
"""
If command receives arguments, then method can be used to set default values.
"""
self.name = None
self.author = None
self.version = None
self.release = None
self.language = None
self.template = None
self.doc_dir = None
def finalize_options(self) -> NoReturn:
"""
If command receive arguments, then method can be used to set final values for arguments.
"""
if self.name is None:
self.name = NAME
if self.author is None:
self.author = AUTHOR
if self.version is None:
self.version = about['__version__']
if self.release is None:
self.release = about['__version__']
if self.language is None:
self.language = 'en'
if self.template is None:
self.template = str(Path('_docs').absolute())
if self.doc_dir is None:
self.doc_dir = str(Path('docs').absolute())
def run(self) -> None:
generate_command = [
'sphinx-quickstart',
'--sep',
'-p', self.name,
'-a', self.author,
'-v', self.version,
'-r', self.release,
'-l', self.language,
'--ext-autodoc',
'--ext-githubpages',
'-t', self.template,
str(self.doc_dir)
]
try:
print(' '.join(generate_command))
subprocess.check_call(generate_command)
except subprocess.CalledProcessError as e:
print(f"Error: Failed to generate documentation with Sphinx: {e}")
raise
class SphinxAutoDoc(Command):
"""
Class responsible for configuration of the Sphinx project and documentation generation.
"""
description = 'Generate documentation for modules.'
user_options = [
('with-magic-methods', None, 'Include magic packages to documentation.'),
('with-private-methods', None, 'Include private methods to documentation'),
('generate-project', None, 'Generate Sphinx project based on configuration.'),
('separate', None, 'Separate modules from sub-modules.'),
('automodules=', None, 'Coma-separated list of auto-modules.')
]
with_magic_methods: bool
with_private_methods: bool
generate_project: bool
separate: bool
automodules: str
@staticmethod
def __get_boolean_value(variable: Union[int, bool]) -> bool:
"""
Get boolean value from status code.
:param variable: Checked variable.
:type variable: Union[int, bool]
:return: True or False for status code and default value for None.
:rtype: bool
"""
if variable == 1:
return True
elif variable == 0:
return False
else:
return variable
def initialize_options(self) -> NoReturn:
"""
If command receive arguments, then method can be used to set default values.
"""
self.with_magic_methods = False
self.with_private_methods = False
self.generate_project = False
self.separate = False
self.automodules = ""
def finalize_options(self) -> NoReturn:
"""
If command receive arguments, then method can be used to set final values for arguments.
"""
self.with_magic_methods = self.__get_boolean_value(self.with_magic_methods)
self.with_private_methods = self.__get_boolean_value(self.with_private_methods)
self.generate_project = self.__get_boolean_value(self.generate_project)
self.separate = self.__get_boolean_value(self.separate)
@staticmethod
def __get_magic_packages(sources_path: str) -> Set[str]:
"""
Get all magic packages from sources.
:param sources_path: Path to sources.
:type sources_path: str
:return: Set of magic methods.
:rtype: Set[str]
"""
magic_packages = set()
for root, folders, files in os.walk(sources_path):
for file in files:
if file.startswith('__') and file.endswith('__.py'):
magic_packages.add(file)
return magic_packages
def __get_magic_excludes(self, sources_path: str) -> List[str]:
"""
Get list of fnmatch excludes.
:param sources_path: Path to sources folder.
:type sources_path: str
:return: Fnmatch excludes list.
:rtype: List[str]
"""
excludes = []
magic_packages = self.__get_magic_packages(sources_path)
for exclude in magic_packages:
excludes.append(f'*{exclude}')
if '*__init__.py' in excludes:
excludes.remove('*__init__.py')
return excludes
def __print_configuration(self) -> NoReturn:
"""
Print configuration used to generate documentation.
"""
print('Generate documentation configuration:')
print(f'\tGenerate project - {self.generate_project}')
print(f'\tSeparate modules from sub-modules - {self.separate}')
print(f'\tAdd private methods - {self.with_private_methods}')
print(f'\tAdd magic methods - {self.with_magic_methods}')
print(f'\tSelected auto-modules - {self.automodules}')
def run(self) -> NoReturn:
"""
Generate Sphinx project and documentation.
"""
docs_path = os.path.join(here, 'docs')
templates = os.path.join(docs_path, '_documentation_templates')
sources_path = os.path.join(here, 'sources')
rel_sources_path = os.path.relpath(sources_path, here)
self.__print_configuration()
cmd = ['sphinx-apidoc', '--templatedir', templates, '--force', '-o', os.path.join(docs_path, 'source')]
if self.generate_project:
cmd.extend(['--full', '-a', '-H', NAME, '-A', AUTHOR, '-V', VERSION, '-R', RELEASE])
if self.with_private_methods:
if self.automodules:
os.environ['SPHINX_APIDOC_OPTIONS'] = self.automodules
cmd.append('--private')
if self.separate:
cmd.append('--separate')
cmd.append(rel_sources_path)
if not self.with_magic_methods:
exclude_packages = ' '.join(self.__get_magic_excludes(sources_path))
cmd.append(exclude_packages)
print('Generate documentation for modules.')
process = subprocess.Popen(cmd)
process.communicate()
successful_message = 'Documentation for modules was successfully generated.'
error_message = 'Error occurred during the documentation generation.'
check_status_code(process.returncode, successful_message, error_message)
cmd_class = {
'prepare_venv': PrepareVirtualEnvironmentCommand,
'sphinx_generate_project': SphinxGenerate,
'sphinx_update_modules': SphinxAutoDoc,
'sphinx_build': BuildDocsCommand
}
command_options = {
'sphinx-generate-project': {
'name': (NAME, 'Specify the project name'),
'author': (AUTHOR, 'Specify the project author'),
'version': (VERSION, 'Specify the project version'),
'release': (RELEASE, 'Specify the project release'),
'language': ('en', 'Specify the project language'),
'template': ('_docs', 'Specify the project template'),
'doc-dir': ('docs', 'Specify the documentation directory'),
},
}
def parse_requirements(file_path):
if os.path.exists(file_path):
with open(file_path, 'r') as f:
requirements = f.read().splitlines()
else:
requirements = []
return requirements
def main():
# Path to the requirements.txt file
requirements_path = 'requirements.txt'
# Parse the requirements from requirements.txt
requirements = parse_requirements(requirements_path)
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
maintainer=AUTHOR,
maintainer_email=EMAIL,
python_requires=REQUIRES_PYTHON,
install_requires=requirements,
url=URL,
platforms=['any'],
packages=find_packages(exclude=['tests', '*.tests', '*.tests.*', 'tests.*']),
include_package_data=True,
license='MIT',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
keywords=['action-demo'],
cmdclass=cmd_class,
command_options=command_options,
)
if __name__ == '__main__':
main()