pybuild.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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{py_ver}__{suf}={mod}{modsuf}'.format(
  45. path=stripext(to_build_root(path, unit)), suf=suf, mod=mod, modsuf=stripext(suf), py_ver=unit.get('_PYTHON_VER')
  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)), unit.get('_PYTHON_VER'), 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. resolved_files = get_resolved_files()
  166. if resolved_files:
  167. resource = "build/external_resources/ruff"
  168. params = ["ruff", "tools/ruff_linter/bin/ruff_linter"]
  169. params += ["FILES"] + resolved_files
  170. params += ["GLOBAL_RESOURCES", resource]
  171. configs = [unit.get('RUFF_CONFIG_PATHS_FILE'), 'build/config/tests/ruff/ruff.toml'] + get_ruff_configs(unit)
  172. params += ['CONFIGS'] + configs
  173. unit.on_add_linter_check(params)
  174. if files and unit.get('STYLE_PYTHON_VALUE') == 'yes' and is_py3(unit):
  175. resolved_files = get_resolved_files()
  176. if resolved_files:
  177. black_cfg = unit.get('STYLE_PYTHON_PYPROJECT_VALUE') or 'build/config/tests/py_style/config.toml'
  178. params = ['black', 'tools/black_linter/black_linter']
  179. params += ['FILES'] + resolved_files
  180. params += ['CONFIGS', black_cfg]
  181. unit.on_add_linter_check(params)
  182. def is_py3(unit):
  183. return unit.get("PYTHON3") == "yes"
  184. def on_py_program(unit, *args):
  185. py_program(unit, is_py3(unit))
  186. def py_program(unit, py3):
  187. """
  188. Documentation: https://wiki.yandex-team.ru/devtools/commandsandvars/py_srcs/#modulpyprogramimakrospymain
  189. """
  190. if py3:
  191. peers = ['library/python/runtime_py3/main']
  192. if unit.get('PYTHON_SQLITE3') != 'no':
  193. peers.append('contrib/tools/python3/Modules/_sqlite')
  194. else:
  195. peers = ['library/python/runtime/main']
  196. if unit.get('PYTHON_SQLITE3') != 'no':
  197. peers.append('contrib/tools/python/src/Modules/_sqlite')
  198. unit.onpeerdir(peers)
  199. if unit.get('MODULE_TYPE') == 'PROGRAM': # can not check DLL
  200. unit.onadd_check_py_imports()
  201. def onpy_srcs(unit, *args):
  202. """
  203. @usage PY_SRCS({| CYTHONIZE_PY} {| CYTHON_C} { | TOP_LEVEL | NAMESPACE ns} Files...)
  204. PY_SRCS() - is rule to build extended versions of Python interpreters and containing all application code in its executable file.
  205. 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.
  206. The main disadvantage is the lack of IDE support; There is also no readline yet.
  207. 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.
  208. 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:
  209. when the interpreter starts, the initialization code will add a custom loader of these modules to sys.meta_path.
  210. 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.
  211. To enable it, add "# cython: profile=True" line to the beginning of every cythonized source.
  212. 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.
  213. Building with pyx automatically registers modules, you do not need to call PY_REGISTER for them
  214. __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.
  215. Example of library declaration with PY_SRCS():
  216. PY2_LIBRARY(mymodule)
  217. 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)
  218. END()
  219. PY_REGISTER honors Python2 and Python3 differences and adjusts itself to Python version of a current module
  220. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipylibrarypy3libraryimakrospysrcs
  221. """
  222. # Each file arg must either be a path, or "${...}/buildpath=modname", where
  223. # "${...}/buildpath" part will be used as a file source in a future macro,
  224. # and "modname" will be used as a module name.
  225. upath = unit.path()[3:]
  226. py3 = is_py3(unit)
  227. py_main_only = unit.get('PROCESS_PY_MAIN_ONLY')
  228. with_py = not unit.get('PYBUILD_NO_PY')
  229. with_pyc = not unit.get('PYBUILD_NO_PYC')
  230. in_proto_library = unit.get('PY_PROTO') or unit.get('PY3_PROTO')
  231. venv = unit.get(YA_IDE_VENV_VAR)
  232. need_gazetteer_peerdir = False
  233. trim = 0
  234. if (
  235. not upath.startswith('contrib/tools/python')
  236. and not upath.startswith('library/python/runtime')
  237. and unit.get('NO_PYTHON_INCLS') != 'yes'
  238. ):
  239. unit.onpeerdir(['contrib/libs/python'])
  240. unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL')
  241. if unit_needs_main:
  242. py_program(unit, py3)
  243. py_namespace_value = unit.get('PY_NAMESPACE_VALUE')
  244. if py_namespace_value == ".":
  245. ns = ""
  246. else:
  247. ns = (unit.get('PY_NAMESPACE_VALUE') or upath.replace('/', '.')) + '.'
  248. cython_coverage = unit.get('CYTHON_COVERAGE') == 'yes'
  249. cythonize_py = False
  250. optimize_proto = unit.get('OPTIMIZE_PY_PROTOS_FLAG') == 'yes'
  251. cython_directives = []
  252. if cython_coverage:
  253. cython_directives += ['-X', 'linetrace=True']
  254. pyxs_c = []
  255. pyxs_c_h = []
  256. pyxs_c_api_h = []
  257. pyxs_cpp = []
  258. pyxs_cpp_h = []
  259. pyxs = pyxs_cpp
  260. swigs_c = []
  261. swigs_cpp = []
  262. swigs = swigs_cpp
  263. pys = []
  264. pyis = []
  265. protos = []
  266. evs = []
  267. fbss = []
  268. py_namespaces = {}
  269. dump_dir = unit.get('PYTHON_BUILD_DUMP_DIR')
  270. dump_output = None
  271. if dump_dir:
  272. import threading
  273. pid = os.getpid()
  274. tid = threading.current_thread().ident
  275. dump_name = '{}-{}.dump'.format(pid, tid)
  276. dump_output = open(os.path.join(dump_dir, dump_name), 'a')
  277. args = iter(args)
  278. for arg in args:
  279. # Namespace directives.
  280. if arg == 'TOP_LEVEL':
  281. ns = ''
  282. elif arg == 'NAMESPACE':
  283. ns = next(args) + '.'
  284. # Cython directives.
  285. elif arg == 'CYTHON_C':
  286. pyxs = pyxs_c
  287. elif arg == 'CYTHON_C_H':
  288. pyxs = pyxs_c_h
  289. elif arg == 'CYTHON_C_API_H':
  290. pyxs = pyxs_c_api_h
  291. elif arg == 'CYTHON_CPP':
  292. pyxs = pyxs_cpp
  293. elif arg == 'CYTHON_CPP_H':
  294. pyxs = pyxs_cpp_h
  295. elif arg == 'CYTHON_DIRECTIVE':
  296. cython_directives += ['-X', next(args)]
  297. elif arg == 'CYTHONIZE_PY':
  298. cythonize_py = True
  299. # SWIG.
  300. elif arg == 'SWIG_C':
  301. swigs = swigs_c
  302. elif arg == 'SWIG_CPP':
  303. swigs = swigs_cpp
  304. # Unsupported but legal PROTO_LIBRARY arguments.
  305. elif arg == 'GLOBAL' or not in_proto_library and arg.endswith('.gztproto'):
  306. pass
  307. elif arg == '_MR':
  308. # GLOB support: convert arcadia-root-relative paths to module-relative
  309. # srcs are assumed to start with ${ARCADIA_ROOT}
  310. trim = len(unit.path()) + 14
  311. # Sources.
  312. else:
  313. main_mod = arg == 'MAIN'
  314. if main_mod:
  315. arg = next(args)
  316. if '=' in arg:
  317. main_py = False
  318. path, mod = arg.split('=', 1)
  319. else:
  320. if trim:
  321. arg = arg[trim:]
  322. if arg.endswith('.gztproto'):
  323. need_gazetteer_peerdir = True
  324. path = '{}.proto'.format(arg[:-9])
  325. else:
  326. path = arg
  327. main_py = path == '__main__.py' or path.endswith('/__main__.py')
  328. if not py3 and unit_needs_main and main_py:
  329. mod = '__main__'
  330. else:
  331. if arg.startswith('../'):
  332. ymake.report_configure_error('PY_SRCS item starts with "../": {!r}'.format(arg))
  333. if arg.startswith('/'):
  334. ymake.report_configure_error('PY_SRCS item starts with "/": {!r}'.format(arg))
  335. continue
  336. mod_name = stripext(arg).replace('/', '.')
  337. if py3 and path.endswith('.py') and is_extended_source_search_enabled(path, unit):
  338. # Dig out real path from the file path. Unit.path is not enough because of SRCDIR and ADDINCL
  339. root_rel_path = rootrel_arc_src(path, unit)
  340. mod_root_path = root_rel_path[: -(len(path) + 1)]
  341. py_namespaces.setdefault(mod_root_path, set()).add(ns if ns else '.')
  342. mod = ns + mod_name
  343. if in_proto_library:
  344. mod = mod.replace('-', '_')
  345. if main_mod:
  346. py_main(unit, mod + ":main")
  347. elif py3 and unit_needs_main and main_py:
  348. py_main(unit, mod)
  349. if py_main_only:
  350. continue
  351. if py3 and mod == '__main__':
  352. ymake.report_configure_error('TOP_LEVEL __main__.py is not allowed in PY3_PROGRAM')
  353. pathmod = (path, mod)
  354. if dump_output is not None:
  355. dump_output.write(
  356. '{path}\t{module}\t{py3}\n'.format(
  357. path=rootrel_arc_src(path, unit), module=mod, py3=1 if py3 else 0
  358. )
  359. )
  360. if path.endswith('.py'):
  361. if cythonize_py:
  362. pyxs.append(pathmod)
  363. else:
  364. pys.append(pathmod)
  365. elif path.endswith('.pyx'):
  366. pyxs.append(pathmod)
  367. elif path.endswith('.proto'):
  368. protos.append(pathmod)
  369. elif path.endswith('.ev'):
  370. evs.append(pathmod)
  371. elif path.endswith('.swg'):
  372. swigs.append(pathmod)
  373. elif path.endswith('.pyi'):
  374. pyis.append(pathmod)
  375. elif path.endswith('.fbs'):
  376. fbss.append(pathmod)
  377. else:
  378. ymake.report_configure_error('in PY_SRCS: unrecognized arg {!r}'.format(path))
  379. if dump_output is not None:
  380. dump_output.close()
  381. if pyxs:
  382. py_files2res = set()
  383. cpp_files2res = set()
  384. # Include map stores files which were included in the processing pyx file,
  385. # to be able to find source code of the included file inside generated file
  386. # for currently processing pyx file.
  387. include_map = collections.defaultdict(set)
  388. if cython_coverage:
  389. def process_pyx(filename, path, out_suffix, with_ext):
  390. # skip generated files
  391. if not is_arc_src(path, unit):
  392. return
  393. # source file
  394. py_files2res.add((filename, path))
  395. # generated
  396. if with_ext is None:
  397. cpp_files2res.add(
  398. (
  399. os.path.splitext(filename)[0] + out_suffix,
  400. os.path.splitext(path)[0] + out_suffix,
  401. )
  402. )
  403. else:
  404. cpp_files2res.add((filename + with_ext + out_suffix, path + with_ext + out_suffix))
  405. # used includes
  406. for entry in parse_pyx_includes(filename, path, unit.resolve('$S')):
  407. py_files2res.add(entry)
  408. include_arc_rel = entry[0]
  409. include_map[filename].add(include_arc_rel)
  410. else:
  411. def process_pyx(filename, path, out_suffix, with_ext):
  412. pass
  413. obj_suff = unit.get('OBJ_SUF')
  414. assert obj_suff is not None
  415. for pyxs, cython, out_suffix, with_ext in [
  416. (pyxs_c, unit.on_buildwith_cython_c_dep, ".c", obj_suff),
  417. (pyxs_c_h, unit.on_buildwith_cython_c_h, ".c", None),
  418. (pyxs_c_api_h, unit.on_buildwith_cython_c_api_h, ".c", None),
  419. (pyxs_cpp, unit.on_buildwith_cython_cpp_dep, ".cpp", obj_suff),
  420. (pyxs_cpp_h, unit.on_buildwith_cython_cpp_h, ".cpp", None),
  421. ]:
  422. for path, mod in pyxs:
  423. filename = rootrel_arc_src(path, unit)
  424. cython_args = [path]
  425. dep = path
  426. if path.endswith('.py'):
  427. pxd = '/'.join(mod.split('.')) + '.pxd'
  428. if unit.resolve_arc_path(pxd):
  429. dep = pxd
  430. cython_args.append(dep)
  431. cython_args += [
  432. '--module-name',
  433. mod,
  434. '--init-suffix',
  435. mangle(mod),
  436. '--source-root',
  437. '${ARCADIA_ROOT}',
  438. # set arcadia root relative __file__ for generated modules
  439. '-X',
  440. 'set_initial_path={}'.format(filename),
  441. ] + cython_directives
  442. cython(cython_args)
  443. py_register(unit, mod, py3)
  444. process_pyx(filename, path, out_suffix, with_ext)
  445. if cythonize_py:
  446. # Lint checks are not added for cythonized files by default, so we must add it here
  447. # as we are doing for regular pys.
  448. _23 = 3 if py3 else 2
  449. add_python_lint_checks(
  450. unit,
  451. _23,
  452. [path for path, mod in pyxs if path.endswith(".py")]
  453. + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split(),
  454. )
  455. if py_files2res:
  456. # Compile original and generated sources into target for proper cython coverage calculation
  457. for files2res in (py_files2res, cpp_files2res):
  458. unit.onresource_files([x for name, path in files2res for x in ('DEST', name, path)])
  459. if include_map:
  460. data = []
  461. prefix = 'resfs/cython/include'
  462. for line in sorted(
  463. '{}/{}={}'.format(prefix, filename, ':'.join(sorted(files)))
  464. for filename, files in six.iteritems(include_map)
  465. ):
  466. data += ['-', line]
  467. unit.onresource(data)
  468. for swigs, on_swig_python in [
  469. (swigs_c, unit.on_swig_python_c),
  470. (swigs_cpp, unit.on_swig_python_cpp),
  471. ]:
  472. for path, mod in swigs:
  473. # Make output prefix basename match swig module name.
  474. prefix = path[: path.rfind('/') + 1] + mod.rsplit('.', 1)[-1]
  475. swg_py = '{}/{}/{}.py'.format('${ARCADIA_BUILD_ROOT}', upath, prefix)
  476. on_swig_python([path, prefix])
  477. onpy_register(unit, mod + '_swg')
  478. onpy_srcs(unit, swg_py + '=' + mod)
  479. if pys:
  480. pys_seen = set()
  481. pys_dups = {m for _, m in pys if (m in pys_seen or pys_seen.add(m))}
  482. if pys_dups:
  483. ymake.report_configure_error('Duplicate(s) is found in the PY_SRCS macro: {}'.format(pys_dups))
  484. res = []
  485. if py3:
  486. mod_list_md5 = md5()
  487. for path, mod in pys:
  488. mod_list_md5.update(six.ensure_binary(mod))
  489. if not (venv and is_extended_source_search_enabled(path, unit)):
  490. dest = 'py/' + mod.replace('.', '/') + '.py'
  491. if with_py:
  492. res += ['DEST', dest, path]
  493. if with_pyc:
  494. root_rel_path = rootrel_arc_src(path, unit)
  495. dst = path + uniq_suffix(path, unit)
  496. unit.on_py3_compile_bytecode([root_rel_path + '-', path, dst])
  497. res += ['DEST', dest + '.yapyc3', dst + '.yapyc3']
  498. if py_namespaces:
  499. # Note: Add md5 to key to prevent key collision if two or more PY_SRCS() used in the same ya.make
  500. ns_res = []
  501. for path, ns in sorted(py_namespaces.items()):
  502. key = '{}/{}/{}'.format(PY_NAMESPACE_PREFIX, mod_list_md5.hexdigest(), path)
  503. namespaces = ':'.join(sorted(ns))
  504. ns_res += ['-', '{}="{}"'.format(key, namespaces)]
  505. unit.onresource(ns_res)
  506. _split_macro_call(unit.onresource_files, res, (3 if with_py else 0) + (3 if with_pyc else 0))
  507. add_python_lint_checks(
  508. unit, 3, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split()
  509. )
  510. else:
  511. for path, mod in pys:
  512. root_rel_path = rootrel_arc_src(path, unit)
  513. if with_py:
  514. key = '/py_modules/' + mod
  515. res += [
  516. path,
  517. key,
  518. '-',
  519. 'resfs/src/{}={}'.format(key, root_rel_path),
  520. ]
  521. if with_pyc:
  522. src = unit.resolve_arc_path(path) or path
  523. dst = path + uniq_suffix(path, unit)
  524. unit.on_py_compile_bytecode([root_rel_path + '-', src, dst])
  525. res += [dst + '.yapyc', '/py_code/' + mod]
  526. _split_macro_call(unit.onresource, res, (4 if with_py else 0) + (2 if with_pyc else 0))
  527. add_python_lint_checks(
  528. unit, 2, [path for path, mod in pys] + unit.get(['_PY_EXTRA_LINT_FILES_VALUE']).split()
  529. )
  530. if pyis:
  531. pyis_seen = set()
  532. pyis_dups = {m for _, m in pyis if (m in pyis_seen or pyis_seen.add(m))}
  533. if pyis_dups:
  534. pyis_dups = ', '.join(name for name in sorted(pyis_dups))
  535. ymake.report_configure_error('Duplicate(s) is found in the PY_SRCS macro: {}'.format(pyis_dups))
  536. res = []
  537. for path, mod in pyis:
  538. dest = 'py/' + mod.replace('.', '/') + '.pyi'
  539. res += ['DEST', dest, path]
  540. unit.onresource_files(res)
  541. use_vanilla_protoc = unit.get('USE_VANILLA_PROTOC') == 'yes'
  542. if use_vanilla_protoc:
  543. cpp_runtime_path = 'contrib/libs/protobuf_std'
  544. py_runtime_path = 'contrib/python/protobuf_std'
  545. builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO
  546. else:
  547. cpp_runtime_path = 'contrib/libs/protobuf'
  548. py_runtime_path = 'contrib/python/protobuf'
  549. builtin_proto_path = cpp_runtime_path + '/' + BUILTIN_PROTO
  550. if protos:
  551. if not upath.startswith(py_runtime_path) and not upath.startswith(builtin_proto_path):
  552. unit.onpeerdir(py_runtime_path)
  553. unit.onpeerdir(unit.get("PY_PROTO_DEPS").split())
  554. proto_paths = [path for path, mod in protos]
  555. unit.on_generate_py_protos_internal(proto_paths)
  556. unit.onpy_srcs(
  557. [
  558. pb2_arg(py_suf, path, mod, unit)
  559. for path, mod in protos
  560. for py_suf in unit.get("PY_PROTO_SUFFIXES").split()
  561. ]
  562. )
  563. if optimize_proto and need_gazetteer_peerdir:
  564. unit.onpeerdir(['kernel/gazetteer/proto'])
  565. if evs:
  566. unit.onpeerdir([cpp_runtime_path])
  567. unit.on_generate_py_evs_internal([path for path, mod in evs])
  568. unit.onpy_srcs([ev_arg(path, mod, unit) for path, mod in evs])
  569. if fbss:
  570. unit.onpeerdir(unit.get('_PY_FBS_DEPS').split())
  571. pysrc_base_name = listid(fbss)
  572. if py3:
  573. unit.onfbs_to_pysrc([pysrc_base_name] + [path for path, _ in fbss])
  574. unit.onsrcs(['GLOBAL', '{}.py3.fbs.pysrc'.format(pysrc_base_name)])
  575. else:
  576. unit.onfbs_to_py2src([pysrc_base_name] + [path for path, _ in fbss])
  577. unit.onsrcs(['GLOBAL', '{}.py2.fbs.pysrc'.format(pysrc_base_name)])
  578. def _check_test_srcs(*args):
  579. used = set(args) & {"NAMESPACE", "TOP_LEVEL", "__main__.py"}
  580. if used:
  581. param = list(used)[0]
  582. ymake.report_configure_error(
  583. 'in TEST_SRCS: you cannot use {} here - it would broke testing machinery'.format(param)
  584. )
  585. def ontest_srcs(unit, *args):
  586. _check_test_srcs(*args)
  587. if unit.get('PY3TEST_BIN' if is_py3(unit) else 'PYTEST_BIN') != 'no':
  588. unit.onpy_srcs(["NAMESPACE", "__tests__"] + list(args))
  589. def onpy_doctests(unit, *args):
  590. """
  591. @usage PY_DOCTESTS(Packages...)
  592. Add to the test doctests for specified Python packages
  593. The packages should be part of a test (listed as sources of the test or its PEERDIRs).
  594. """
  595. if unit.get('PY3TEST_BIN' if is_py3(unit) else 'PYTEST_BIN') != 'no':
  596. unit.onresource(['-', 'PY_DOCTEST_PACKAGES="{}"'.format(' '.join(args))])
  597. def py_register(unit, func, py3):
  598. if py3:
  599. unit.on_py3_register([func])
  600. else:
  601. unit.on_py_register([func])
  602. def onpy_register(unit, *args):
  603. """
  604. @usage: PY_REGISTER([package.]module_name)
  605. Python knows about which built-ins can be imported, due to their registration in the Assembly or at the start of the interpreter.
  606. All modules from the sources listed in PY_SRCS() are registered automatically.
  607. To register the modules from the sources in the SRCS(), you need to use PY_REGISTER().
  608. PY_REGISTER(module_name) initializes module globally via call to initmodule_name()
  609. PY_REGISTER(package.module_name) initializes module in the specified package
  610. It renames its init function with CFLAGS(-Dinitmodule_name=init7package11module_name)
  611. or CFLAGS(-DPyInit_module_name=PyInit_7package11module_name)
  612. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#makrospyregister
  613. """
  614. py3 = is_py3(unit)
  615. for name in args:
  616. assert '=' not in name, name
  617. py_register(unit, name, py3)
  618. if '.' in name:
  619. shortname = name.rsplit('.', 1)[1]
  620. if py3:
  621. unit.oncflags(['-DPyInit_{}=PyInit_{}'.format(shortname, mangle(name))])
  622. else:
  623. unit.oncflags(['-Dinit{}=init{}'.format(shortname, mangle(name))])
  624. def py_main(unit, arg):
  625. if unit.get('IGNORE_PY_MAIN'):
  626. return
  627. unit_needs_main = unit.get('MODULE_TYPE') in ('PROGRAM', 'DLL')
  628. if unit_needs_main:
  629. py_program(unit, is_py3(unit))
  630. unit.onresource(['-', 'PY_MAIN={}'.format(arg)])
  631. def onpy_main(unit, arg):
  632. """
  633. @usage: PY_MAIN(package.module[:func])
  634. Specifies the module or function from which to start executing a python program
  635. Documentation: https://wiki.yandex-team.ru/arcadia/python/pysrcs/#modulipyprogrampy3programimakrospymain
  636. """
  637. arg = arg.replace('/', '.')
  638. if ':' not in arg:
  639. arg += ':main'
  640. py_main(unit, arg)
  641. def onpy_constructor(unit, arg):
  642. """
  643. @usage: PY_CONSTRUCTOR(package.module[:func])
  644. Specifies the module or function which will be started before python's main()
  645. init() is expected in the target module if no function is specified
  646. Can be considered as __attribute__((constructor)) for python
  647. """
  648. if ':' not in arg:
  649. arg = arg + '=init'
  650. else:
  651. arg[arg.index(':')] = '='
  652. unit.onresource(['-', 'py/constructors/{}'.format(arg)])
  653. def onpy_enums_serialization(unit, *args):
  654. ns = ''
  655. args = iter(args)
  656. for arg in args:
  657. # Namespace directives.
  658. if arg == 'NAMESPACE':
  659. ns = next(args)
  660. else:
  661. unit.on_py_enum_serialization_to_json(arg)
  662. unit.on_py_enum_serialization_to_py(arg)
  663. filename = arg.rsplit('.', 1)[0] + '.py'
  664. if len(ns) != 0:
  665. onpy_srcs(unit, 'NAMESPACE', ns, filename)
  666. else:
  667. onpy_srcs(unit, filename)
  668. def oncpp_enums_serialization(unit, *args):
  669. args = iter(args)
  670. for arg in args:
  671. # Namespace directives.
  672. if arg == 'NAMESPACE':
  673. next(args)
  674. else:
  675. unit.ongenerate_enum_serialization_with_header(arg)