pybuild.py 28 KB

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