pybuild.py 28 KB

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