nots.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import os
  2. import ymake
  3. import ytest
  4. from _common import resolve_common_const, get_norm_unit_path, rootrel_arc_src, to_yesno
  5. # 1 is 60 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  6. # 0.5 is 120 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  7. # 0.2 is 300 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  8. ESLINT_FILE_PROCESSING_TIME_DEFAULT = 0.2 # seconds per file
  9. class PluginLogger(object):
  10. def __init__(self):
  11. self.unit = None
  12. self.prefix = ""
  13. def reset(self, unit, prefix=""):
  14. self.unit = unit
  15. self.prefix = prefix
  16. def get_state(self):
  17. return (self.unit, self.prefix)
  18. def _stringify_messages(self, messages):
  19. parts = []
  20. for m in messages:
  21. if m is None:
  22. parts.append("None")
  23. else:
  24. parts.append(m if isinstance(m, str) else repr(m))
  25. # cyan color (code 36) for messages
  26. return "\033[0;32m{}\033[0;49m\n\033[0;36m{}\033[0;49m".format(self.prefix, " ".join(parts))
  27. def info(self, *messages):
  28. if self.unit:
  29. self.unit.message(["INFO", self._stringify_messages(messages)])
  30. def warn(self, *messages):
  31. if self.unit:
  32. self.unit.message(["WARN", self._stringify_messages(messages)])
  33. def error(self, *messages):
  34. if self.unit:
  35. self.unit.message(["ERROR", self._stringify_messages(messages)])
  36. def print_vars(self, *variables):
  37. if self.unit:
  38. values = ["{}={}".format(v, self.unit.get(v)) for v in variables]
  39. self.info("\n".join(values))
  40. logger = PluginLogger()
  41. def _with_report_configure_error(fn):
  42. def _wrapper(*args, **kwargs):
  43. last_state = logger.get_state()
  44. unit = args[0]
  45. logger.reset(unit if unit.get("TS_LOG") == "yes" else None, fn.__name__)
  46. try:
  47. fn(*args, **kwargs)
  48. except Exception as exc:
  49. ymake.report_configure_error(str(exc))
  50. if unit.get("TS_RAISE") == "yes":
  51. raise
  52. else:
  53. unit.message(["WARN", "Configure error is reported. Add -DTS_RAISE to see actual exception"])
  54. finally:
  55. logger.reset(*last_state)
  56. return _wrapper
  57. def _build_directives(name, flags, paths):
  58. # type: (str, list[str]|tuple[str], list[str]) -> str
  59. parts = [p for p in [name] + (flags or []) if p]
  60. parts_str = ";".join(parts)
  61. expressions = ['${{{parts}:"{path}"}}'.format(parts=parts_str, path=path) for path in paths]
  62. return " ".join(expressions)
  63. def _build_cmd_input_paths(paths, hide=False, disable_include_processor=False):
  64. # type: (list[str]|tuple[str], bool, bool) -> str
  65. hide_part = "hide" if hide else ""
  66. disable_ip_part = "context=TEXT" if disable_include_processor else ""
  67. return _build_directives("input", [hide_part, disable_ip_part], paths)
  68. def _create_pm(unit):
  69. from lib.nots.package_manager import manager
  70. sources_path = unit.path()
  71. module_path = unit.get("MODDIR")
  72. if unit.get("TS_TEST_FOR"):
  73. sources_path = unit.get("TS_TEST_FOR_DIR")
  74. module_path = unit.get("TS_TEST_FOR_PATH")
  75. return manager(
  76. sources_path=unit.resolve(sources_path),
  77. build_root="$B",
  78. build_path=unit.path().replace("$S", "$B", 1),
  79. contribs_path=unit.get("NPM_CONTRIBS_PATH"),
  80. nodejs_bin_path=None,
  81. script_path=None,
  82. module_path=module_path,
  83. )
  84. def _create_erm_json(unit):
  85. from lib.nots.erm_json_lite import ErmJsonLite
  86. erm_packages_path = unit.get("ERM_PACKAGES_PATH")
  87. path = unit.resolve(unit.resolve_arc_path(erm_packages_path))
  88. return ErmJsonLite.load(path)
  89. @_with_report_configure_error
  90. def on_set_append_with_directive(unit, var_name, dir, *values):
  91. wrapped = ['${{{dir}:"{v}"}}'.format(dir=dir, v=v) for v in values]
  92. __set_append(unit, var_name, " ".join(wrapped))
  93. @_with_report_configure_error
  94. def on_from_npm_lockfiles(unit, *args):
  95. from lib.nots.package_manager.base import PackageManagerError
  96. pm = _create_pm(unit)
  97. lf_paths = []
  98. for lf_path in args:
  99. abs_lf_path = unit.resolve(unit.resolve_arc_path(lf_path))
  100. if abs_lf_path:
  101. lf_paths.append(abs_lf_path)
  102. elif unit.get("TS_STRICT_FROM_NPM_LOCKFILES") == "yes":
  103. ymake.report_configure_error("lockfile not found: {}".format(lf_path))
  104. try:
  105. for pkg in pm.extract_packages_meta_from_lockfiles(lf_paths):
  106. unit.on_from_npm([pkg.tarball_url, pkg.sky_id, pkg.integrity, pkg.integrity_algorithm, pkg.tarball_path])
  107. except PackageManagerError as e:
  108. logger.warn(str(e))
  109. pass
  110. def _check_nodejs_version(unit, major):
  111. if major < 14:
  112. raise Exception(
  113. "Node.js {} is unsupported. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major)
  114. )
  115. if major < 18:
  116. unit.message(
  117. [
  118. "WARN",
  119. "Node.js {} is deprecated. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major),
  120. ]
  121. )
  122. @_with_report_configure_error
  123. def on_peerdir_ts_resource(unit, *resources):
  124. pm = _create_pm(unit)
  125. pj = pm.load_package_json_from_dir(pm.sources_path)
  126. erm_json = _create_erm_json(unit)
  127. dirs = []
  128. nodejs_version = _select_matching_version(erm_json, "nodejs", pj.get_nodejs_version())
  129. _check_nodejs_version(unit, nodejs_version.major)
  130. for tool in resources:
  131. dir_name = erm_json.canonize_name(tool)
  132. if erm_json.use_resource_directly(tool):
  133. # raises the configuration error when the version is unsupported
  134. _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool), dep_is_required=True)
  135. elif tool == "nodejs":
  136. dirs.append(os.path.join("build", "platform", dir_name, str(nodejs_version)))
  137. _set_resource_vars(unit, erm_json, tool, nodejs_version)
  138. elif erm_json.is_resource_multiplatform(tool):
  139. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  140. sb_resources = [
  141. sbr for sbr in erm_json.get_sb_resources(tool, v) if sbr.get("nodejs") == nodejs_version.major
  142. ]
  143. nodejs_dir = "NODEJS_{}".format(nodejs_version.major)
  144. if len(sb_resources) > 0:
  145. dirs.append(os.path.join("build", "external_resources", dir_name, str(v), nodejs_dir))
  146. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  147. else:
  148. unit.message(["WARN", "Missing {}@{} for {}".format(tool, str(v), nodejs_dir)])
  149. else:
  150. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  151. dirs.append(os.path.join("build", "external_resources", dir_name, str(v)))
  152. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  153. if dirs:
  154. unit.onpeerdir(dirs)
  155. @_with_report_configure_error
  156. def on_ts_configure(unit):
  157. # type: (Unit) -> None
  158. from lib.nots.package_manager.base import PackageJson
  159. from lib.nots.package_manager.base.utils import build_pj_path
  160. from lib.nots.typescript import TsConfig
  161. tsconfig_paths = unit.get("TS_CONFIG_PATH").split()
  162. # for use in CMD as inputs
  163. __set_append(
  164. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(tsconfig_paths, hide=True, disable_include_processor=True)
  165. )
  166. mod_dir = unit.get("MODDIR")
  167. cur_dir = unit.get("TS_TEST_FOR_PATH") if unit.get("TS_TEST_FOR") else mod_dir
  168. pj_path = build_pj_path(unit.resolve(unit.resolve_arc_path(cur_dir)))
  169. dep_paths = PackageJson.load(pj_path).get_dep_paths_by_names()
  170. # reversed for using the first tsconfig as the config for include processor (legacy)
  171. for tsconfig_path in reversed(tsconfig_paths):
  172. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  173. if not abs_tsconfig_path:
  174. raise Exception("tsconfig not found: {}".format(tsconfig_path))
  175. tsconfig = TsConfig.load(abs_tsconfig_path)
  176. config_files = tsconfig.inline_extend(dep_paths)
  177. config_files = _resolve_module_files(unit, mod_dir, config_files)
  178. use_tsconfig_outdir = unit.get("TS_CONFIG_USE_OUTDIR") == "yes"
  179. tsconfig.validate(use_tsconfig_outdir)
  180. # add tsconfig files from which root tsconfig files were extended
  181. __set_append(
  182. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(config_files, hide=True, disable_include_processor=True)
  183. )
  184. # region include processor
  185. unit.set(["TS_CONFIG_ROOT_DIR", tsconfig.compiler_option("rootDir")]) # also for hermione
  186. if use_tsconfig_outdir:
  187. unit.set(["TS_CONFIG_OUT_DIR", tsconfig.compiler_option("outDir")]) # also for hermione
  188. unit.set(["TS_CONFIG_SOURCE_MAP", to_yesno(tsconfig.compiler_option("sourceMap"))])
  189. unit.set(["TS_CONFIG_DECLARATION", to_yesno(tsconfig.compiler_option("declaration"))])
  190. unit.set(["TS_CONFIG_DECLARATION_MAP", to_yesno(tsconfig.compiler_option("declarationMap"))])
  191. unit.set(["TS_CONFIG_PRESERVE_JSX", to_yesno(tsconfig.compiler_option("jsx") == "preserve")])
  192. # endregion
  193. _filter_inputs_by_rules_from_tsconfig(unit, tsconfig)
  194. _setup_eslint(unit)
  195. _setup_tsc_typecheck(unit, tsconfig_paths)
  196. def __set_append(unit, var_name, value):
  197. # type: (Unit, str, str|list[str]|tuple[str]) -> None
  198. """
  199. SET_APPEND() python naive implementation - append value/values to the list of values
  200. """
  201. previous_value = unit.get(var_name) or ""
  202. value_in_str = " ".join(value) if isinstance(value, list) or isinstance(value, tuple) else value
  203. new_value = previous_value + " " + value_in_str
  204. unit.set([var_name, new_value])
  205. def __strip_prefix(prefix, line):
  206. # type: (str, str) -> str
  207. if line.startswith(prefix):
  208. prefix_len = len(prefix)
  209. return line[prefix_len:]
  210. return line
  211. def _filter_inputs_by_rules_from_tsconfig(unit, tsconfig):
  212. """
  213. Reduce file list from the TS_GLOB_FILES variable following tsconfig.json rules
  214. """
  215. mod_dir = unit.get("MODDIR")
  216. target_path = os.path.join("${ARCADIA_ROOT}", mod_dir, "") # To have "/" in the end
  217. all_files = [__strip_prefix(target_path, f) for f in unit.get("TS_GLOB_FILES").split(" ")]
  218. filtered_files = tsconfig.filter_files(all_files)
  219. __set_append(unit, "TS_INPUT_FILES", [os.path.join(target_path, f) for f in filtered_files])
  220. def _get_ts_test_data_dirs(unit):
  221. return sorted(
  222. set(
  223. [
  224. os.path.dirname(rootrel_arc_src(p, unit))
  225. for p in (ytest.get_values_list(unit, "_TS_TEST_DATA_VALUE") or [])
  226. ]
  227. )
  228. )
  229. def _resolve_config_path(unit, test_runner, rel_to):
  230. config_path = unit.get("ESLINT_CONFIG_PATH") if test_runner == "eslint" else unit.get("TS_TEST_CONFIG_PATH")
  231. arc_config_path = unit.resolve_arc_path(config_path)
  232. abs_config_path = unit.resolve(arc_config_path)
  233. if not abs_config_path:
  234. raise Exception("{} config not found: {}".format(test_runner, config_path))
  235. unit.onsrcs([arc_config_path])
  236. abs_rel_to = unit.resolve(unit.resolve_arc_path(unit.get(rel_to)))
  237. return os.path.relpath(abs_config_path, start=abs_rel_to)
  238. def _is_tests_enabled(unit):
  239. if unit.get("TIDY") == "yes":
  240. return False
  241. return True
  242. def _get_test_runner_handlers():
  243. return {
  244. "jest": _add_jest_ts_test,
  245. "hermione": _add_hermione_ts_test,
  246. "playwright": _add_playwright_ts_test,
  247. }
  248. def _add_jest_ts_test(unit, test_runner, test_files, deps, test_record):
  249. test_record.update(
  250. {
  251. "CONFIG-PATH": _resolve_config_path(unit, test_runner, rel_to="TS_TEST_FOR_PATH"),
  252. }
  253. )
  254. _add_test(unit, test_runner, test_files, deps, test_record)
  255. def _add_hermione_ts_test(unit, test_runner, test_files, deps, test_record):
  256. test_tags = sorted(set(["ya:fat", "ya:external", "ya:noretries"] + ytest.get_values_list(unit, "TEST_TAGS_VALUE")))
  257. test_requirements = sorted(set(["network:full"] + ytest.get_values_list(unit, "TEST_REQUIREMENTS_VALUE")))
  258. test_record.update(
  259. {
  260. "SIZE": "LARGE",
  261. "TAG": ytest.serialize_list(test_tags),
  262. "REQUIREMENTS": ytest.serialize_list(test_requirements),
  263. "CONFIG-PATH": _resolve_config_path(unit, test_runner, rel_to="TS_TEST_FOR_PATH"),
  264. }
  265. )
  266. _add_test(unit, test_runner, test_files, deps, test_record)
  267. def _add_playwright_ts_test(unit, test_runner, test_files, deps, test_record):
  268. test_record.update(
  269. {
  270. "CONFIG-PATH": _resolve_config_path(unit, test_runner, rel_to="TS_TEST_FOR_PATH"),
  271. }
  272. )
  273. _add_test(unit, test_runner, test_files, deps, test_record)
  274. def _setup_eslint(unit):
  275. if not _is_tests_enabled(unit):
  276. return
  277. if unit.get("_NO_LINT_VALUE") == "none":
  278. return
  279. lint_files = ytest.get_values_list(unit, "_TS_LINT_SRCS_VALUE")
  280. if not lint_files:
  281. return
  282. unit.on_peerdir_ts_resource("eslint")
  283. user_recipes = unit.get("TEST_RECIPES_VALUE")
  284. unit.on_setup_extract_node_modules_recipe(unit.get("MODDIR"))
  285. mod_dir = unit.get("MODDIR")
  286. lint_files = _resolve_module_files(unit, mod_dir, lint_files)
  287. deps = _create_pm(unit).get_peers_from_package_json()
  288. test_record = {
  289. "ESLINT_CONFIG_PATH": _resolve_config_path(unit, "eslint", rel_to="MODDIR"),
  290. "LINT-FILE-PROCESSING-TIME": str(ESLINT_FILE_PROCESSING_TIME_DEFAULT),
  291. }
  292. _add_test(unit, "eslint", lint_files, deps, test_record, mod_dir)
  293. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  294. def _setup_tsc_typecheck(unit, tsconfig_paths: list[str]):
  295. if not _is_tests_enabled(unit):
  296. return
  297. if unit.get("_TS_TYPECHECK_VALUE") == "none":
  298. return
  299. typecheck_files = ytest.get_values_list(unit, "TS_INPUT_FILES")
  300. if not typecheck_files:
  301. return
  302. tsconfig_path = tsconfig_paths[0]
  303. if len(tsconfig_paths) > 1:
  304. tsconfig_path = unit.get("_TS_TYPECHECK_TSCONFIG")
  305. if not tsconfig_path:
  306. macros = " or ".join([f"TS_TYPECHECK({p})" for p in tsconfig_paths])
  307. raise Exception(f"Module uses several tsconfig files, specify which one to use for typecheck: {macros}")
  308. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  309. if not abs_tsconfig_path:
  310. raise Exception(f"tsconfig for typecheck not found: {tsconfig_path}")
  311. unit.on_peerdir_ts_resource("typescript")
  312. user_recipes = unit.get("TEST_RECIPES_VALUE")
  313. unit.on_setup_install_node_modules_recipe()
  314. unit.on_setup_extract_output_tars_recipe([unit.get("MODDIR")])
  315. _add_test(
  316. unit,
  317. test_type="tsc_typecheck",
  318. test_files=[resolve_common_const(f) for f in typecheck_files],
  319. deps=_create_pm(unit).get_peers_from_package_json(),
  320. test_record={"TS_CONFIG_PATH": tsconfig_path},
  321. test_cwd=unit.get("MODDIR"),
  322. )
  323. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  324. def _resolve_module_files(unit, mod_dir, file_paths):
  325. mod_dir_with_sep_len = len(mod_dir) + 1
  326. resolved_files = []
  327. for path in file_paths:
  328. resolved = rootrel_arc_src(path, unit)
  329. if resolved.startswith(mod_dir):
  330. resolved = resolved[mod_dir_with_sep_len:]
  331. resolved_files.append(resolved)
  332. return resolved_files
  333. def _add_test(unit, test_type, test_files, deps=None, test_record=None, test_cwd=None):
  334. from lib.nots.package_manager import constants
  335. def sort_uniq(text):
  336. return sorted(set(text))
  337. recipes_lines = ytest.format_recipes(unit.get("TEST_RECIPES_VALUE")).strip().splitlines()
  338. if recipes_lines:
  339. deps = deps or []
  340. deps.extend([os.path.dirname(r.strip().split(" ")[0]) for r in recipes_lines])
  341. if deps:
  342. joined_deps = "\n".join(deps)
  343. logger.info(f"{test_type} deps: \n{joined_deps}")
  344. unit.ondepends(deps)
  345. test_dir = get_norm_unit_path(unit)
  346. full_test_record = {
  347. # Key to discover suite (see devtools/ya/test/explore/__init__.py#gen_suite)
  348. "SCRIPT-REL-PATH": test_type,
  349. # Test name as shown in PR check, should be unique inside one module
  350. "TEST-NAME": test_type.lower(),
  351. "TEST-TIMEOUT": unit.get("TEST_TIMEOUT") or "",
  352. "TEST-ENV": ytest.prepare_env(unit.get("TEST_ENV_VALUE")),
  353. "TESTED-PROJECT-NAME": os.path.splitext(unit.filename())[0],
  354. "TEST-RECIPES": ytest.prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  355. "SOURCE-FOLDER-PATH": test_dir,
  356. "BUILD-FOLDER-PATH": test_dir,
  357. "BINARY-PATH": os.path.join(test_dir, unit.filename()),
  358. "SPLIT-FACTOR": unit.get("TEST_SPLIT_FACTOR") or "",
  359. "FORK-MODE": unit.get("TEST_FORK_MODE") or "",
  360. "SIZE": unit.get("TEST_SIZE_NAME") or "",
  361. "TEST-DATA": ytest.serialize_list(ytest.get_values_list(unit, "TEST_DATA_VALUE")),
  362. "TEST-FILES": ytest.serialize_list(test_files),
  363. "TEST-CWD": test_cwd or "",
  364. "TAG": ytest.serialize_list(ytest.get_values_list(unit, "TEST_TAGS_VALUE")),
  365. "REQUIREMENTS": ytest.serialize_list(ytest.get_values_list(unit, "TEST_REQUIREMENTS_VALUE")),
  366. "NODEJS-ROOT-VAR-NAME": unit.get("NODEJS-ROOT-VAR-NAME"),
  367. "NODE-MODULES-BUNDLE-FILENAME": constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME,
  368. "CUSTOM-DEPENDENCIES": " ".join(sort_uniq((deps or []) + ytest.get_values_list(unit, "TEST_DEPENDS_VALUE"))),
  369. }
  370. if test_record:
  371. full_test_record.update(test_record)
  372. data = ytest.dump_test(unit, full_test_record)
  373. if data:
  374. unit.set_property(["DART_DATA", data])
  375. def _set_resource_vars(unit, erm_json, tool, version, nodejs_major=None):
  376. # type: (any, ErmJsonLite, Version, str|None, int|None) -> None
  377. resource_name = erm_json.canonize_name(tool).upper()
  378. # example: NODEJS_12_18_4 | HERMIONE_7_0_4_NODEJS_18
  379. version_str = str(version).replace(".", "_")
  380. yamake_resource_name = "{}_{}".format(resource_name, version_str)
  381. if erm_json.is_resource_multiplatform(tool):
  382. yamake_resource_name += "_NODEJS_{}".format(nodejs_major)
  383. yamake_resource_var = "{}_RESOURCE_GLOBAL".format(yamake_resource_name)
  384. unit.set(["{}_ROOT".format(resource_name), "${}".format(yamake_resource_var)])
  385. unit.set(["{}-ROOT-VAR-NAME".format(resource_name), yamake_resource_var])
  386. def _select_matching_version(erm_json, resource_name, range_str, dep_is_required=False):
  387. # type: (ErmJsonLite, str, str, bool) -> Version
  388. if dep_is_required and range_str is None:
  389. raise Exception(
  390. "Please install the '{tool}' package to the project. Run the command:\n"
  391. " ya tool nots add -D {tool}".format(tool=resource_name)
  392. )
  393. try:
  394. version = erm_json.select_version_of(resource_name, range_str)
  395. if version:
  396. return version
  397. raise ValueError("There is no allowed version to satisfy this range: '{}'".format(range_str))
  398. except Exception as error:
  399. toolchain_versions = erm_json.get_versions_of(erm_json.get_resource(resource_name))
  400. raise Exception(
  401. "Requested {} version range '{}' could not be satisfied. \n"
  402. "Please use a range that would include one of the following: {}. \n"
  403. "For further details please visit the link: {} \nOriginal error: {} \n".format(
  404. resource_name,
  405. range_str,
  406. ", ".join(map(str, toolchain_versions)),
  407. "https://docs.yandex-team.ru/frontend-in-arcadia/_generated/toolchain",
  408. str(error),
  409. )
  410. )
  411. @_with_report_configure_error
  412. def on_prepare_deps_configure(unit):
  413. # Originally this peerdir was in .conf file
  414. # but it kept taking default value of NPM_CONTRIBS_PATH
  415. # before it was updated by CUSTOM_CONTRIB_TYPESCRIPT()
  416. # so I moved it here.
  417. unit.onpeerdir(unit.get("NPM_CONTRIBS_PATH"))
  418. pm = _create_pm(unit)
  419. pj = pm.load_package_json_from_dir(pm.sources_path)
  420. has_deps = pj.has_dependencies()
  421. ins, outs = pm.calc_prepare_deps_inouts(unit.get("_TARBALLS_STORE"), has_deps)
  422. if pj.has_dependencies():
  423. unit.onpeerdir(pm.get_local_peers_from_package_json())
  424. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  425. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  426. else:
  427. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", [], sorted(outs)))
  428. unit.set(["_PREPARE_DEPS_CMD", "$_PREPARE_NO_DEPS_CMD"])
  429. @_with_report_configure_error
  430. def on_node_modules_configure(unit):
  431. pm = _create_pm(unit)
  432. pj = pm.load_package_json_from_dir(pm.sources_path)
  433. if pj.has_dependencies():
  434. unit.onpeerdir(pm.get_local_peers_from_package_json())
  435. local_cli = unit.get("TS_LOCAL_CLI") == "yes"
  436. ins, outs = pm.calc_node_modules_inouts(local_cli)
  437. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  438. if not unit.get("TS_TEST_FOR"):
  439. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  440. if pj.get_use_prebuilder():
  441. unit.on_peerdir_ts_resource("@yatool/prebuilder")
  442. unit.set(
  443. [
  444. "_YATOOL_PREBUILDER_ARG",
  445. "--yatool-prebuilder-path $YATOOL_PREBUILDER_ROOT/node_modules/@yatool/prebuilder",
  446. ]
  447. )
  448. # YATOOL_PREBUILDER_0_7_0_RESOURCE_GLOBAL
  449. prebuilder_major = unit.get("YATOOL_PREBUILDER-ROOT-VAR-NAME").split("_")[2]
  450. logger.info(f"Detected prebuilder \033[0;32mv{prebuilder_major}.x.x\033[0;49m")
  451. if prebuilder_major == "0":
  452. # TODO: FBP-1408
  453. lf = pm.load_lockfile_from_dir(pm.sources_path)
  454. is_valid, invalid_keys = lf.validate_has_addons_flags()
  455. if not is_valid:
  456. ymake.report_configure_error(
  457. "Project is configured to use @yatool/prebuilder. \n"
  458. + "Some packages in the pnpm-lock.yaml are misconfigured.\n"
  459. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix lockfile.\n"
  460. + "All packages with `requiresBuild:true` have to be marked with `hasAddons:true/false`.\n"
  461. + "Misconfigured keys: \n"
  462. + " - "
  463. + "\n - ".join(invalid_keys)
  464. )
  465. else:
  466. lf = pm.load_lockfile_from_dir(pm.sources_path)
  467. requires_build_packages = lf.get_requires_build_packages()
  468. is_valid, validation_messages = pj.validate_prebuilds(requires_build_packages)
  469. if not is_valid:
  470. ymake.report_configure_error(
  471. "Project is configured to use @yatool/prebuilder. \n"
  472. + "Some packages are misconfigured.\n"
  473. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix pnpm-lock.yaml and package.json.\n"
  474. + "Validation details: \n"
  475. + "\n".join(validation_messages)
  476. )
  477. @_with_report_configure_error
  478. def on_ts_test_for_configure(unit, test_runner, default_config, node_modules_filename):
  479. if not _is_tests_enabled(unit):
  480. return
  481. if unit.enabled('TS_COVERAGE'):
  482. unit.on_peerdir_ts_resource("nyc")
  483. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  484. unit.onpeerdir([for_mod_path])
  485. unit.on_setup_extract_node_modules_recipe([for_mod_path])
  486. unit.on_setup_extract_output_tars_recipe([for_mod_path])
  487. root = "$B" if test_runner == "hermione" else "$(BUILD_ROOT)"
  488. unit.set(["TS_TEST_NM", os.path.join(root, for_mod_path, node_modules_filename)])
  489. config_path = unit.get("TS_TEST_CONFIG_PATH")
  490. if not config_path:
  491. config_path = os.path.join(for_mod_path, default_config)
  492. unit.set(["TS_TEST_CONFIG_PATH", config_path])
  493. test_record = _add_ts_resources_to_test_record(
  494. unit,
  495. {
  496. "TS-TEST-FOR-PATH": for_mod_path,
  497. "TS-TEST-DATA-DIRS": ytest.serialize_list(_get_ts_test_data_dirs(unit)),
  498. "TS-TEST-DATA-DIRS-RENAME": unit.get("_TS_TEST_DATA_DIRS_RENAME_VALUE"),
  499. },
  500. )
  501. test_files = ytest.get_values_list(unit, "_TS_TEST_SRCS_VALUE")
  502. test_files = _resolve_module_files(unit, unit.get("MODDIR"), test_files)
  503. if not test_files:
  504. ymake.report_configure_error("No tests found")
  505. return
  506. deps = _create_pm(unit).get_peers_from_package_json()
  507. add_ts_test = _get_test_runner_handlers()[test_runner]
  508. add_ts_test(unit, test_runner, test_files, deps, test_record)
  509. @_with_report_configure_error
  510. def on_validate_ts_test_for_args(unit, for_mod, root):
  511. # FBP-1085
  512. is_arc_root = root == "${ARCADIA_ROOT}"
  513. is_rel_for_mod = for_mod.startswith(".")
  514. if is_arc_root and is_rel_for_mod:
  515. ymake.report_configure_error(
  516. "You are using a relative path for a module. "
  517. + "You have to add RELATIVE key, like (RELATIVE {})".format(for_mod)
  518. )
  519. @_with_report_configure_error
  520. def on_set_ts_test_for_vars(unit, for_mod):
  521. unit.set(["TS_TEST_FOR", "yes"])
  522. unit.set(["TS_TEST_FOR_DIR", unit.resolve_arc_path(for_mod)])
  523. unit.set(["TS_TEST_FOR_PATH", rootrel_arc_src(for_mod, unit)])
  524. def _add_ts_resources_to_test_record(unit, test_record):
  525. erm_json = _create_erm_json(unit)
  526. for tool in erm_json.list_npm_packages():
  527. tool_resource_label = "{}-ROOT-VAR-NAME".format(tool.upper())
  528. tool_resource_value = unit.get(tool_resource_label)
  529. if tool_resource_value:
  530. test_record[tool_resource_label] = tool_resource_value
  531. return test_record
  532. @_with_report_configure_error
  533. def on_ts_files(unit, *files):
  534. new_cmds = ['$COPY_CMD ${{input;context=TEXT:"{0}"}} ${{output;noauto:"{0}"}}'.format(f) for f in files]
  535. all_cmds = unit.get("_TS_FILES_COPY_CMD")
  536. if all_cmds:
  537. new_cmds.insert(0, all_cmds)
  538. unit.set(["_TS_FILES_COPY_CMD", " && ".join(new_cmds)])
  539. @_with_report_configure_error
  540. def on_ts_package_check_files(unit):
  541. ts_files = unit.get("_TS_FILES_COPY_CMD")
  542. if ts_files == "":
  543. ymake.report_configure_error(
  544. "\n"
  545. "In the TS_PACKAGE module, you should define at least one file using the TS_FILES() macro.\n"
  546. "Docs: https://docs.yandex-team.ru/frontend-in-arcadia/references/TS_PACKAGE#ts-files."
  547. )
  548. @_with_report_configure_error
  549. def on_depends_on_mod(unit):
  550. if unit.get("_TS_TEST_DEPENDS_ON_BUILD"):
  551. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  552. unit.ondepends([for_mod_path])