pybuild.py 30 KB

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