pybuild.py 28 KB

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