pybuild.py 28 KB

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