pybuild.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. import os
  2. import collections
  3. from hashlib import md5
  4. import ymake
  5. from _common import stripext, rootrel_arc_src, tobuilddir, listid, resolve_to_ymake_path, generate_chunks, pathid
  6. YA_IDE_VENV_VAR = 'YA_IDE_VENV'
  7. PY_NAMESPACE_PREFIX = 'py/namespace'
  8. BUILTIN_PROTO = 'builtin_proto'
  9. def is_arc_src(src, unit):
  10. return (
  11. src.startswith('${ARCADIA_ROOT}/') or
  12. src.startswith('${CURDIR}/') or
  13. unit.resolve_arc_path(src).startswith('$S/')
  14. )
  15. def is_extended_source_search_enabled(path, unit):
  16. if not is_arc_src(path, unit):
  17. return False
  18. if unit.get('NO_EXTENDED_SOURCE_SEARCH') == 'yes':
  19. return False
  20. return True
  21. def to_build_root(path, unit):
  22. if is_arc_src(path, unit):
  23. return '${ARCADIA_BUILD_ROOT}/' + rootrel_arc_src(path, unit)
  24. return path
  25. def uniq_suffix(path, unit):
  26. upath = unit.path()
  27. if '/' not in path:
  28. return ''
  29. return '.{}'.format(pathid(path)[:4])
  30. def pb2_arg(suf, path, mod, unit):
  31. return '{path}__int__{suf}={mod}{modsuf}'.format(
  32. path=stripext(to_build_root(path, unit)),
  33. suf=suf,
  34. mod=mod,
  35. modsuf=stripext(suf)
  36. )
  37. def proto_arg(path, mod, unit):
  38. return '{}.proto={}'.format(stripext(to_build_root(path, unit)), mod)
  39. def pb_cc_arg(suf, path, unit):
  40. return '{}{suf}'.format(stripext(to_build_root(path, unit)), suf=suf)
  41. def ev_cc_arg(path, unit):
  42. return '{}.ev.pb.cc'.format(stripext(to_build_root(path, unit)))
  43. def ev_arg(path, mod, unit):
  44. return '{}__int___ev_pb2.py={}_ev_pb2'.format(stripext(to_build_root(path, unit)), mod)
  45. def mangle(name):
  46. if '.' not in name:
  47. return name
  48. return ''.join('{}{}'.format(len(s), s) for s in name.split('.'))
  49. def parse_pyx_includes(filename, path, source_root, seen=None):
  50. normpath = lambda *x: os.path.normpath(os.path.join(*x))
  51. abs_path = normpath(source_root, filename)
  52. seen = seen or set()
  53. if abs_path in seen:
  54. return
  55. seen.add(abs_path)
  56. if not os.path.exists(abs_path):
  57. # File might be missing, because it might be generated
  58. return
  59. with open(abs_path, 'rb') as f:
  60. # Don't parse cimports and etc - irrelevant for cython, it's linker work
  61. includes = ymake.parse_cython_includes(f.read())
  62. abs_dirname = os.path.dirname(abs_path)
  63. # All includes are relative to the file which include
  64. path_dirname = os.path.dirname(path)
  65. file_dirname = os.path.dirname(filename)
  66. for incfile in includes:
  67. abs_path = normpath(abs_dirname, incfile)
  68. if os.path.exists(abs_path):
  69. incname, incpath = normpath(file_dirname, incfile), normpath(path_dirname, incfile)
  70. yield (incname, incpath)
  71. # search for includes in the included files
  72. for e in parse_pyx_includes(incname, incpath, source_root, seen):
  73. yield e
  74. else:
  75. # There might be arcadia root or cython relative include.
  76. # Don't treat such file as missing, because there must be PEERDIR on py_library
  77. # which contains it.
  78. for path in [
  79. source_root,
  80. source_root + "/contrib/tools/cython/Cython/Includes",
  81. ]:
  82. if os.path.exists(normpath(path, incfile)):
  83. break
  84. else:
  85. ymake.report_configure_error("'{}' includes missing file: {} ({})".format(path, incfile, abs_path))
  86. def has_pyx(args):
  87. return any(arg.endswith('.pyx') for arg in args)
  88. def get_srcdir(path, unit):
  89. return rootrel_arc_src(path, unit)[:-len(path)].rstrip('/')
  90. def add_python_lint_checks(unit, py_ver, files):
  91. def get_resolved_files():
  92. resolved_files = []
  93. for path in files:
  94. resolved = unit.resolve_arc_path([path])
  95. if resolved.startswith('$S'): # path was resolved as source file.
  96. resolved_files.append(resolved)
  97. return resolved_files
  98. if unit.get('LINT_LEVEL_VALUE') == "none":
  99. no_lint_allowed_paths = (
  100. "contrib/",
  101. "devtools/",
  102. "junk/",
  103. # temporary allowed, TODO: remove
  104. "taxi/uservices/",
  105. "travel/",
  106. "market/report/lite/", # MARKETOUT-38662, deadline: 2021-08-12
  107. "passport/backend/oauth/", # PASSP-35982
  108. )
  109. upath = unit.path()[3:]
  110. if not upath.startswith(no_lint_allowed_paths):
  111. ymake.report_configure_error("NO_LINT() is allowed only in " + ", ".join(no_lint_allowed_paths))
  112. if files and unit.get('LINT_LEVEL_VALUE') not in ("none", "none_internal"):
  113. resolved_files = get_resolved_files()
  114. flake8_cfg = 'build/config/tests/flake8/flake8.conf'
  115. unit.onadd_check(["flake8.py{}".format(py_ver), flake8_cfg] + resolved_files)
  116. if files and unit.get('STYLE_PYTHON_VALUE') == 'yes' and is_py3(unit):
  117. resolved_files = get_resolved_files()
  118. black_cfg = 'devtools/ya/handlers/style/python_style_config.toml'
  119. unit.onadd_check(['black', black_cfg] + resolved_files)
  120. def is_py3(unit):
  121. return unit.get("PYTHON3") == "yes"
  122. def on_py_program(unit, *args):
  123. py_program(unit, is_py3(unit))
  124. def py_program(unit, py3):
  125. """
  126. Documentation: https://wiki.yandex-team.ru/devtools/commandsandvars/py_srcs/#modulpyprogramimakrospymain
  127. """
  128. if py3:
  129. peers = ['library/python/runtime_py3/main']
  130. if unit.get('PYTHON_SQLITE3') != 'no':
  131. peers.append('contrib/tools/python3/src/Modules/_sqlite')
  132. else:
  133. peers = ['library/python/runtime/main']
  134. if unit.get('PYTHON_SQLITE3') != 'no':
  135. peers.append('contrib/tools/python/src/Modules/_sqlite')
  136. unit.onpeerdir(peers)
  137. if unit.get('MODULE_TYPE') == 'PROGRAM': # can not check DLL
  138. unit.onadd_check_py_imports()
  139. def onpy_srcs(unit, *args):
  140. """
  141. @usage PY_SRCS({| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...)
  142. PY_SRCS() - is rule to build extended versions of Python interpreters and containing all application code in its executable file. It can be used to collect only the executables but not shared libraries, and, in particular, not to collect the modules that are imported using import directive.
  143. The main disadvantage is the lack of IDE support; There is also no readline yet.
  144. The application can be collect from any of the sources from which the C library, and with the help of PY_SRCS .py , .pyx,.proto and .swg files.
  145. At the same time extensions for Python on C language generating from .pyx and .swg, will be registered in Python's as built-in modules, and sources on .py are stored as static data: when the interpreter starts, the initialization code will add a custom loader of these modules to sys.meta_path.
  146. By default .pyx files are collected as C++-extensions. To collect them as C (similar to BUILDWITH_CYTHON_C, but with the ability to specify namespace), you must specify the Directive CYTHON_C.
  147. Building with pyx automatically registers modules, you do not need to call PY_REGISTER for them
  148. __init__.py never required, but if present (and specified in PY_SRCS), it will be imported when you import package modules with __init__.py Oh.
  149. Example of library declaration with PY_SRCS():
  150. PY2_LIBRARY(mymodule)
  151. PY_SRCS(a.py sub/dir/b.py e.proto sub/dir/f.proto c.pyx sub/dir/d.pyx g.swg sub/dir/h.swg)
  152. END()
  153. PY_REGISTER honors Python2 and Python3 differences and adjusts itself to Python version of a current module
  154. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipylibrarypy3libraryimakrospysrcs
  155. """
  156. # Each file arg must either be a path, or "${...}/buildpath=modname", where
  157. # "${...}/buildpath" part will be used as a file source in a future macro,
  158. # and "modname" will be used as a module name.
  159. upath = unit.path()[3:]
  160. py3 = is_py3(unit)
  161. py_main_only = unit.get('PROCESS_PY_MAIN_ONLY')
  162. with_py = not unit.get('PYBUILD_NO_PY')
  163. with_pyc = not unit.get('PYBUILD_NO_PYC')
  164. in_proto_library = unit.get('PY_PROTO') or unit.get('PY3_PROTO')
  165. venv = unit.get(YA_IDE_VENV_VAR)
  166. need_gazetteer_peerdir = False
  167. trim = 0
  168. if not upath.startswith('contrib/tools/python') and not upath.startswith('library/python/runtime') and unit.get('NO_PYTHON_INCLS') != 'yes':
  169. unit.onpeerdir(['contrib/libs/python'])
  170. unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL')
  171. if unit_needs_main:
  172. py_program(unit, py3)
  173. py_namespace_value = unit.get('PY_NAMESPACE_VALUE')
  174. if py_namespace_value == ".":
  175. ns = ""
  176. else:
  177. ns = (unit.get('PY_NAMESPACE_VALUE') or upath.replace('/', '.')) + '.'
  178. cython_coverage = unit.get('CYTHON_COVERAGE') == 'yes'
  179. cythonize_py = False
  180. optimize_proto = unit.get('OPTIMIZE_PY_PROTOS_FLAG') == 'yes'
  181. cython_directives = []
  182. if cython_coverage:
  183. cython_directives += ['-X', 'linetrace=True']
  184. pyxs_c = []
  185. pyxs_c_h = []
  186. pyxs_c_api_h = []
  187. pyxs_cpp = []
  188. pyxs = pyxs_cpp
  189. swigs_c = []
  190. swigs_cpp = []
  191. swigs = swigs_cpp
  192. pys = []
  193. protos = []
  194. evs = []
  195. fbss = []
  196. py_namespaces = {}
  197. dump_dir = unit.get('PYTHON_BUILD_DUMP_DIR')
  198. dump_output = None
  199. if dump_dir:
  200. import thread
  201. pid = os.getpid()
  202. tid = thread.get_ident()
  203. dump_name = '{}-{}.dump'.format(pid, tid)
  204. dump_output = open(os.path.join(dump_dir, dump_name), 'a')
  205. args = iter(args)
  206. for arg in args:
  207. # Namespace directives.
  208. if arg == 'TOP_LEVEL':
  209. ns = ''
  210. elif arg == 'NAMESPACE':
  211. ns = next(args) + '.'
  212. # Cython directives.
  213. elif arg == 'CYTHON_C':
  214. pyxs = pyxs_c
  215. elif arg == 'CYTHON_C_H':
  216. pyxs = pyxs_c_h
  217. elif arg == 'CYTHON_C_API_H':
  218. pyxs = pyxs_c_api_h
  219. elif arg == 'CYTHON_CPP':
  220. pyxs = pyxs_cpp
  221. elif arg == 'CYTHON_DIRECTIVE':
  222. cython_directives += ['-X', next(args)]
  223. elif arg == 'CYTHONIZE_PY':
  224. cythonize_py = True
  225. # SWIG.
  226. elif arg == 'SWIG_C':
  227. swigs = swigs_c
  228. elif arg == 'SWIG_CPP':
  229. swigs = swigs_cpp
  230. # Unsupported but legal PROTO_LIBRARY arguments.
  231. elif arg == 'GLOBAL' or not in_proto_library and arg.endswith('.gztproto'):
  232. pass
  233. elif arg == '_MR':
  234. # GLOB support: convert arcadia-root-relative paths to module-relative
  235. # srcs are assumed to start with ${ARCADIA_ROOT}
  236. trim = len(unit.path()) + 14
  237. # Sources.
  238. else:
  239. main_mod = arg == 'MAIN'
  240. if main_mod:
  241. arg = next(args)
  242. if '=' in arg:
  243. main_py = False
  244. path, mod = arg.split('=', 1)
  245. else:
  246. if trim:
  247. arg = arg[trim:]
  248. if arg.endswith('.gztproto'):
  249. need_gazetteer_peerdir = True
  250. path = '{}.proto'.format(arg[:-9])
  251. else:
  252. path = arg
  253. main_py = (path == '__main__.py' or path.endswith('/__main__.py'))
  254. if not py3 and unit_needs_main and main_py:
  255. mod = '__main__'
  256. else:
  257. if arg.startswith('../'):
  258. ymake.report_configure_error('PY_SRCS item starts with "../": {!r}'.format(arg))
  259. if arg.startswith('/'):
  260. ymake.report_configure_error('PY_SRCS item starts with "/": {!r}'.format(arg))
  261. continue
  262. mod_name = stripext(arg).replace('/', '.')
  263. if py3 and path.endswith('.py') and is_extended_source_search_enabled(path, unit):
  264. # Dig out real path from the file path. Unit.path is not enough because of SRCDIR and ADDINCL
  265. root_rel_path = rootrel_arc_src(path, unit)
  266. mod_root_path = root_rel_path[:-(len(path) + 1)]
  267. py_namespaces.setdefault(mod_root_path, set()).add(ns if ns else '.')
  268. mod = ns + mod_name
  269. if main_mod:
  270. py_main(unit, mod + ":main")
  271. elif py3 and unit_needs_main and main_py:
  272. py_main(unit, mod)
  273. if py_main_only:
  274. continue
  275. if py3 and mod == '__main__':
  276. ymake.report_configure_error('TOP_LEVEL __main__.py is not allowed in PY3_PROGRAM')
  277. pathmod = (path, mod)
  278. if dump_output is not None:
  279. dump_output.write('{path}\t{module}\t{py3}\n'.format(path=rootrel_arc_src(path, unit), module=mod, py3=1 if py3 else 0))
  280. if path.endswith('.py'):
  281. if cythonize_py:
  282. pyxs.append(pathmod)
  283. else:
  284. pys.append(pathmod)
  285. elif path.endswith('.pyx'):
  286. pyxs.append(pathmod)
  287. elif path.endswith('.proto'):
  288. protos.append(pathmod)
  289. elif path.endswith('.ev'):
  290. evs.append(pathmod)
  291. elif path.endswith('.swg'):
  292. swigs.append(pathmod)
  293. # Allow pyi files in PY_SRCS for autocomplete in IDE, but skip it during building
  294. elif path.endswith('.pyi'):
  295. pass
  296. elif path.endswith('.fbs'):
  297. fbss.append(pathmod)
  298. else:
  299. ymake.report_configure_error('in PY_SRCS: unrecognized arg {!r}'.format(path))
  300. if dump_output is not None:
  301. dump_output.close()
  302. if pyxs:
  303. files2res = set()
  304. # Include map stores files which were included in the processing pyx file,
  305. # to be able to find source code of the included file inside generated file
  306. # for currently processing pyx file.
  307. include_map = collections.defaultdict(set)
  308. if cython_coverage:
  309. def process_pyx(filename, path, out_suffix, noext):
  310. # skip generated files
  311. if not is_arc_src(path, unit):
  312. return
  313. # source file
  314. files2res.add((filename, path))
  315. # generated
  316. if noext:
  317. files2res.add((os.path.splitext(filename)[0] + out_suffix, os.path.splitext(path)[0] + out_suffix))
  318. else:
  319. files2res.add((filename + out_suffix, path + out_suffix))
  320. # used includes
  321. for entry in parse_pyx_includes(filename, path, unit.resolve('$S')):
  322. files2res.add(entry)
  323. include_arc_rel = entry[0]
  324. include_map[filename].add(include_arc_rel)
  325. else:
  326. def process_pyx(filename, path, out_suffix, noext):
  327. pass
  328. for pyxs, cython, out_suffix, noext in [
  329. (pyxs_c, unit.on_buildwith_cython_c_dep, ".c", False),
  330. (pyxs_c_h, unit.on_buildwith_cython_c_h, ".c", True),
  331. (pyxs_c_api_h, unit.on_buildwith_cython_c_api_h, ".c", True),
  332. (pyxs_cpp, unit.on_buildwith_cython_cpp_dep, ".cpp", False),
  333. ]:
  334. for path, mod in pyxs:
  335. filename = rootrel_arc_src(path, unit)
  336. cython_args = [path]
  337. dep = path
  338. if path.endswith('.py'):
  339. pxd = '/'.join(mod.split('.')) + '.pxd'
  340. if unit.resolve_arc_path(pxd):
  341. dep = pxd
  342. cython_args.append(dep)
  343. cython_args += [
  344. '--module-name', mod,
  345. '--init-suffix', mangle(mod),
  346. '--source-root', '${ARCADIA_ROOT}',
  347. # set arcadia root relative __file__ for generated modules
  348. '-X', 'set_initial_path={}'.format(filename),
  349. ] + cython_directives
  350. cython(cython_args)
  351. py_register(unit, mod, py3)
  352. process_pyx(filename, path, out_suffix, noext)
  353. if files2res:
  354. # Compile original and generated sources into target for proper cython coverage calculation
  355. unit.onresource_files([x for name, path in files2res for x in ('DEST', name, path)])
  356. if include_map:
  357. data = []
  358. prefix = 'resfs/cython/include'
  359. for line in sorted('{}/{}={}'.format(prefix, filename, ':'.join(sorted(files))) for filename, files in include_map.iteritems()):
  360. data += ['-', line]
  361. unit.onresource(data)
  362. for swigs, on_swig_python in [
  363. (swigs_c, unit.on_swig_python_c),
  364. (swigs_cpp, unit.on_swig_python_cpp),
  365. ]:
  366. for path, mod in swigs:
  367. # Make output prefix basename match swig module name.
  368. prefix = path[:path.rfind('/') + 1] + mod.rsplit('.', 1)[-1]
  369. swg_py = '{}/{}/{}.py'.format('${ARCADIA_BUILD_ROOT}', upath, prefix)
  370. on_swig_python([path, prefix])
  371. onpy_register(unit, mod + '_swg')
  372. onpy_srcs(unit, swg_py + '=' + mod)
  373. if pys:
  374. pys_seen = set()
  375. pys_dups = {m for _, m in pys if (m in pys_seen or pys_seen.add(m))}
  376. if pys_dups:
  377. ymake.report_configure_error('Duplicate(s) is found in the PY_SRCS macro: {}'.format(pys_dups))
  378. res = []
  379. if py3:
  380. mod_list_md5 = md5()
  381. for path, mod in pys:
  382. mod_list_md5.update(mod)
  383. if not (venv and is_extended_source_search_enabled(path, unit)):
  384. dest = 'py/' + mod.replace('.', '/') + '.py'
  385. if with_py:
  386. res += ['DEST', dest, path]
  387. if with_pyc:
  388. root_rel_path = rootrel_arc_src(path, unit)
  389. dst = path + uniq_suffix(path, unit)
  390. unit.on_py3_compile_bytecode([root_rel_path + '-', path, dst])
  391. res += ['DEST', dest + '.yapyc3', dst + '.yapyc3']
  392. if py_namespaces:
  393. # Note: Add md5 to key to prevent key collision if two or more PY_SRCS() used in the same ya.make
  394. ns_res = []
  395. for path, ns in sorted(py_namespaces.items()):
  396. key = '{}/{}/{}'.format(PY_NAMESPACE_PREFIX, mod_list_md5.hexdigest(), path)
  397. namespaces = ':'.join(sorted(ns))
  398. ns_res += ['-', '{}="{}"'.format(key, namespaces)]
  399. unit.onresource(ns_res)
  400. unit.onresource_files(res)
  401. add_python_lint_checks(unit, 3, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split())
  402. else:
  403. for path, mod in pys:
  404. root_rel_path = rootrel_arc_src(path, unit)
  405. if with_py:
  406. key = '/py_modules/' + mod
  407. res += [
  408. path, key,
  409. '-', 'resfs/src/{}={}'.format(key, root_rel_path),
  410. ]
  411. if with_pyc:
  412. src = unit.resolve_arc_path(path) or path
  413. dst = path + uniq_suffix(path, unit)
  414. unit.on_py_compile_bytecode([root_rel_path + '-', src, dst])
  415. res += [dst + '.yapyc', '/py_code/' + mod]
  416. unit.onresource(res)
  417. add_python_lint_checks(unit, 2, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split())
  418. use_vanilla_protoc = unit.get('USE_VANILLA_PROTOC') == 'yes'
  419. if use_vanilla_protoc:
  420. cpp_runtime_path = 'contrib/libs/protobuf_std'
  421. py_runtime_path = 'contrib/python/protobuf_std'
  422. builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO
  423. else:
  424. cpp_runtime_path = 'contrib/libs/protobuf'
  425. py_runtime_path = 'contrib/python/protobuf'
  426. builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO
  427. if protos:
  428. if not upath.startswith(py_runtime_path) and not upath.startswith(builtin_proto_path):
  429. unit.onpeerdir(py_runtime_path)
  430. unit.onpeerdir(unit.get("PY_PROTO_DEPS").split())
  431. proto_paths = [path for path, mod in protos]
  432. unit.on_generate_py_protos_internal(proto_paths)
  433. unit.onpy_srcs([
  434. pb2_arg(py_suf, path, mod, unit)
  435. for path, mod in protos
  436. for py_suf in unit.get("PY_PROTO_SUFFIXES").split()
  437. ])
  438. if optimize_proto and need_gazetteer_peerdir:
  439. unit.onpeerdir(['kernel/gazetteer/proto'])
  440. if evs:
  441. unit.onpeerdir([cpp_runtime_path])
  442. unit.on_generate_py_evs_internal([path for path, mod in evs])
  443. unit.onpy_srcs([ev_arg(path, mod, unit) for path, mod in evs])
  444. if fbss:
  445. unit.onpeerdir(unit.get('_PY_FBS_DEPS').split())
  446. pysrc_base_name = listid(fbss)
  447. unit.onfbs_to_pysrc([pysrc_base_name] + [path for path, _ in fbss])
  448. unit.onsrcs(['GLOBAL', '{}.fbs.pysrc'.format(pysrc_base_name)])
  449. def _check_test_srcs(*args):
  450. used = set(args) & {"NAMESPACE", "TOP_LEVEL", "__main__.py"}
  451. if used:
  452. param = list(used)[0]
  453. ymake.report_configure_error('in TEST_SRCS: you cannot use {} here - it would broke testing machinery'.format(param))
  454. def ontest_srcs(unit, *args):
  455. _check_test_srcs(*args)
  456. if unit.get('PY3TEST_BIN' if is_py3(unit) else 'PYTEST_BIN') != 'no':
  457. unit.onpy_srcs(["NAMESPACE", "__tests__"] + list(args))
  458. def onpy_doctests(unit, *args):
  459. """
  460. @usage PY_DOCTEST(Packages...)
  461. Add to the test doctests for specified Python packages
  462. The packages should be part of a test (listed as sources of the test or its PEERDIRs).
  463. """
  464. if unit.get('PY3TEST_BIN' if is_py3(unit) else 'PYTEST_BIN') != 'no':
  465. unit.onresource(['-', 'PY_DOCTEST_PACKAGES="{}"'.format(' '.join(args))])
  466. def py_register(unit, func, py3):
  467. if py3:
  468. unit.on_py3_register([func])
  469. else:
  470. unit.on_py_register([func])
  471. def onpy_register(unit, *args):
  472. """
  473. @usage: PY_REGISTER([package.]module_name)
  474. Python knows about which built-ins can be imported, due to their registration in the Assembly or at the start of the interpreter.
  475. All modules from the sources listed in PY_SRCS() are registered automatically.
  476. To register the modules from the sources in the SRCS(), you need to use PY_REGISTER().
  477. PY_REGISTER(module_name) initializes module globally via call to initmodule_name()
  478. PY_REGISTER(package.module_name) initializes module in the specified package
  479. It renames its init function with CFLAGS(-Dinitmodule_name=init7package11module_name)
  480. or CFLAGS(-DPyInit_module_name=PyInit_7package11module_name)
  481. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#makrospyregister
  482. """
  483. py3 = is_py3(unit)
  484. for name in args:
  485. assert '=' not in name, name
  486. py_register(unit, name, py3)
  487. if '.' in name:
  488. shortname = name.rsplit('.', 1)[1]
  489. if py3:
  490. unit.oncflags(['-DPyInit_{}=PyInit_{}'.format(shortname, mangle(name))])
  491. else:
  492. unit.oncflags(['-Dinit{}=init{}'.format(shortname, mangle(name))])
  493. def py_main(unit, arg):
  494. if unit.get('IGNORE_PY_MAIN'):
  495. return
  496. unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL')
  497. if unit_needs_main:
  498. py_program(unit, is_py3(unit))
  499. unit.onresource(['-', 'PY_MAIN={}'.format(arg)])
  500. def onpy_main(unit, arg):
  501. """
  502. @usage: PY_MAIN(package.module[:func])
  503. Specifies the module or function from which to start executing a python program
  504. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipyprogrampy3programimakrospymain
  505. """
  506. arg = arg.replace('/', '.')
  507. if ':' not in arg:
  508. arg += ':main'
  509. py_main(unit, arg)
  510. def onpy_constructor(unit, arg):
  511. """
  512. @usage: PY_CONSTRUCTOR(package.module[:func])
  513. Specifies the module or function which will be started before python's main()
  514. init() is expected in the target module if no function is specified
  515. Can be considered as __attribute__((constructor)) for python
  516. """
  517. if ':' not in arg:
  518. arg = arg + '=init'
  519. else:
  520. arg[arg.index(':')] = '='
  521. unit.onresource(['-', 'py/constructors/{}'.format(arg)])
  522. def onpy_enums_serialization(unit, *args):
  523. ns = ''
  524. args = iter(args)
  525. for arg in args:
  526. # Namespace directives.
  527. if arg == 'NAMESPACE':
  528. ns = next(args)
  529. else:
  530. unit.on_py_enum_serialization_to_json(arg)
  531. unit.on_py_enum_serialization_to_py(arg)
  532. filename = arg.rsplit('.', 1)[0] + '.py'
  533. if len(ns) != 0:
  534. onpy_srcs(unit, 'NAMESPACE', ns, filename)
  535. else:
  536. onpy_srcs(unit, filename)
  537. def oncpp_enums_serialization(unit, *args):
  538. args = iter(args)
  539. for arg in args:
  540. # Namespace directives.
  541. if arg == 'NAMESPACE':
  542. next(args)
  543. else:
  544. unit.ongenerate_enum_serialization_with_header(arg)