nots.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. import os
  2. import ymake
  3. import ytest
  4. from _common import 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 \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. expressions = ["${{{parts}:\"{path}\"}}".format(parts=";".join(parts), path=path) for path in paths]
  61. return " ".join(expressions)
  62. def _build_cmd_input_paths(paths, hide=False, disable_include_processor=False):
  63. # type: (list[str]|tuple[str], bool, bool) -> str
  64. hide_part = "hide" if hide else ""
  65. disable_ip_part = "context=TEXT" if disable_include_processor else ""
  66. return _build_directives("input", [hide_part, disable_ip_part], paths)
  67. def _create_pm(unit):
  68. from lib.nots.package_manager import manager
  69. sources_path = unit.path()
  70. module_path = unit.get("MODDIR")
  71. if unit.get("TS_TEST_FOR"):
  72. sources_path = unit.get("TS_TEST_FOR_DIR")
  73. module_path = unit.get("TS_TEST_FOR_PATH")
  74. return manager(
  75. sources_path=unit.resolve(sources_path),
  76. build_root="$B",
  77. build_path=unit.path().replace("$S", "$B", 1),
  78. contribs_path=unit.get("NPM_CONTRIBS_PATH"),
  79. nodejs_bin_path=None,
  80. script_path=None,
  81. module_path=module_path,
  82. )
  83. def _create_erm_json(unit):
  84. from lib.nots.erm_json_lite import ErmJsonLite
  85. erm_packages_path = unit.get("ERM_PACKAGES_PATH")
  86. path = unit.resolve(unit.resolve_arc_path(erm_packages_path))
  87. return ErmJsonLite.load(path)
  88. @_with_report_configure_error
  89. def on_from_npm_lockfiles(unit, *args):
  90. from lib.nots.package_manager.base import PackageManagerError
  91. pm = _create_pm(unit)
  92. lf_paths = []
  93. for lf_path in args:
  94. abs_lf_path = unit.resolve(unit.resolve_arc_path(lf_path))
  95. if abs_lf_path:
  96. lf_paths.append(abs_lf_path)
  97. elif unit.get("TS_STRICT_FROM_NPM_LOCKFILES") == "yes":
  98. ymake.report_configure_error("lockfile not found: {}".format(lf_path))
  99. try:
  100. for pkg in pm.extract_packages_meta_from_lockfiles(lf_paths):
  101. unit.on_from_npm([pkg.tarball_url, pkg.sky_id, pkg.integrity, pkg.integrity_algorithm, pkg.tarball_path])
  102. except PackageManagerError as e:
  103. logger.warn(str(e))
  104. pass
  105. def _check_nodejs_version(unit, major):
  106. if major < 14:
  107. raise Exception(
  108. "Node.js {} is unsupported. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major)
  109. )
  110. if major < 18:
  111. unit.message(
  112. [
  113. "WARN",
  114. "Node.js {} is deprecated. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major),
  115. ]
  116. )
  117. @_with_report_configure_error
  118. def on_peerdir_ts_resource(unit, *resources):
  119. pm = _create_pm(unit)
  120. pj = pm.load_package_json_from_dir(pm.sources_path)
  121. erm_json = _create_erm_json(unit)
  122. dirs = []
  123. nodejs_version = _select_matching_version(erm_json, "nodejs", pj.get_nodejs_version())
  124. _check_nodejs_version(unit, nodejs_version.major)
  125. for tool in resources:
  126. dir_name = erm_json.canonize_name(tool)
  127. if erm_json.use_resource_directly(tool):
  128. # raises the configuration error when the version is unsupported
  129. _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool), dep_is_required=True)
  130. elif tool == "nodejs":
  131. dirs.append(os.path.join("build", "platform", dir_name, str(nodejs_version)))
  132. _set_resource_vars(unit, erm_json, tool, nodejs_version)
  133. elif erm_json.is_resource_multiplatform(tool):
  134. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  135. sb_resources = [
  136. sbr for sbr in erm_json.get_sb_resources(tool, v) if sbr.get("nodejs") == nodejs_version.major
  137. ]
  138. nodejs_dir = "NODEJS_{}".format(nodejs_version.major)
  139. if len(sb_resources) > 0:
  140. dirs.append(os.path.join("build", "external_resources", dir_name, str(v), nodejs_dir))
  141. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  142. else:
  143. unit.message(["WARN", "Missing {}@{} for {}".format(tool, str(v), nodejs_dir)])
  144. else:
  145. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  146. dirs.append(os.path.join("build", "external_resources", dir_name, str(v)))
  147. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  148. if dirs:
  149. unit.onpeerdir(dirs)
  150. @_with_report_configure_error
  151. def on_ts_configure(unit, *tsconfig_paths):
  152. # type: (Unit, *str) -> None
  153. from lib.nots.package_manager.base import PackageJson
  154. from lib.nots.package_manager.base.utils import build_pj_path
  155. from lib.nots.typescript import TsConfig
  156. # for use in CMD as inputs
  157. __set_append(
  158. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(tsconfig_paths, hide=True, disable_include_processor=True)
  159. )
  160. mod_dir = unit.get("MODDIR")
  161. cur_dir = unit.get("TS_TEST_FOR_PATH") if unit.get("TS_TEST_FOR") else mod_dir
  162. pj_path = build_pj_path(unit.resolve(unit.resolve_arc_path(cur_dir)))
  163. dep_paths = PackageJson.load(pj_path).get_dep_paths_by_names()
  164. # reversed for using the first tsconfig as the config for include processor (legacy)
  165. for tsconfig_path in reversed(tsconfig_paths):
  166. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  167. if not abs_tsconfig_path:
  168. raise Exception("tsconfig not found: {}".format(tsconfig_path))
  169. tsconfig = TsConfig.load(abs_tsconfig_path)
  170. config_files = tsconfig.inline_extend(dep_paths)
  171. config_files = _resolve_module_files(unit, mod_dir, config_files)
  172. use_tsconfig_outdir = unit.get("TS_CONFIG_USE_OUTDIR") == "yes"
  173. tsconfig.validate(use_tsconfig_outdir)
  174. # add tsconfig files from which root tsconfig files were extended
  175. __set_append(
  176. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(config_files, hide=True, disable_include_processor=True)
  177. )
  178. # region include processor
  179. unit.set(["TS_CONFIG_ROOT_DIR", tsconfig.compiler_option("rootDir")]) # also for hermione
  180. if use_tsconfig_outdir:
  181. unit.set(["TS_CONFIG_OUT_DIR", tsconfig.compiler_option("outDir")]) # also for hermione
  182. unit.set(["TS_CONFIG_SOURCE_MAP", to_yesno(tsconfig.compiler_option("sourceMap"))])
  183. unit.set(["TS_CONFIG_DECLARATION", to_yesno(tsconfig.compiler_option("declaration"))])
  184. unit.set(["TS_CONFIG_DECLARATION_MAP", to_yesno(tsconfig.compiler_option("declarationMap"))])
  185. unit.set(["TS_CONFIG_PRESERVE_JSX", to_yesno(tsconfig.compiler_option("jsx") == "preserve")])
  186. # endregion
  187. _filter_inputs_by_rules_from_tsconfig(unit, tsconfig)
  188. _setup_eslint(unit)
  189. def __set_append(unit, var_name, value):
  190. # type: (Unit, str, str|list[str]|tuple[str]) -> None
  191. """
  192. SET_APPEND() python naive implementation - append value/values to the list of values
  193. """
  194. previous_value = unit.get(var_name) or ""
  195. value_in_str = " ".join(value) if isinstance(value, list) or isinstance(value, tuple) else value
  196. new_value = previous_value + " " + value_in_str
  197. unit.set([var_name, new_value])
  198. def __strip_prefix(prefix, line):
  199. # type: (str, str) -> str
  200. if line.startswith(prefix):
  201. prefix_len = len(prefix)
  202. return line[prefix_len:]
  203. return line
  204. def _filter_inputs_by_rules_from_tsconfig(unit, tsconfig):
  205. """
  206. Reduce file list from the TS_GLOB_FILES variable following tsconfig.json rules
  207. """
  208. mod_dir = unit.get("MODDIR")
  209. target_path = os.path.join("${ARCADIA_ROOT}", mod_dir, "") # To have "/" in the end
  210. all_files = [__strip_prefix(target_path, f) for f in unit.get("TS_GLOB_FILES").split(" ")]
  211. filtered_files = tsconfig.filter_files(all_files)
  212. __set_append(unit, "TS_INPUT_FILES", [os.path.join(target_path, f) for f in filtered_files])
  213. def _get_ts_test_data_dirs(unit):
  214. return sorted(
  215. set(
  216. [
  217. os.path.dirname(rootrel_arc_src(p, unit))
  218. for p in (ytest.get_values_list(unit, "_TS_TEST_DATA_VALUE") or [])
  219. ]
  220. )
  221. )
  222. def _resolve_config_path(unit, test_runner, rel_to):
  223. config_path = unit.get("ESLINT_CONFIG_PATH") if test_runner == "eslint" else unit.get("TS_TEST_CONFIG_PATH")
  224. arc_config_path = unit.resolve_arc_path(config_path)
  225. abs_config_path = unit.resolve(arc_config_path)
  226. if not abs_config_path:
  227. raise Exception("{} config not found: {}".format(test_runner, config_path))
  228. unit.onsrcs([arc_config_path])
  229. abs_rel_to = unit.resolve(unit.resolve_arc_path(unit.get(rel_to)))
  230. return os.path.relpath(abs_config_path, start=abs_rel_to)
  231. def _is_tests_enabled(unit):
  232. if unit.get("TIDY") == "yes":
  233. return False
  234. return True
  235. def _get_test_runner_handlers():
  236. return {
  237. "jest": _add_jest_ts_test,
  238. "hermione": _add_hermione_ts_test,
  239. }
  240. def _add_jest_ts_test(unit, test_runner, test_files, deps, test_record):
  241. test_record.update(
  242. {
  243. "CONFIG-PATH": _resolve_config_path(unit, test_runner, rel_to="TS_TEST_FOR_PATH"),
  244. }
  245. )
  246. _add_test(unit, test_runner, test_files, deps, test_record)
  247. def _add_hermione_ts_test(unit, test_runner, test_files, deps, test_record):
  248. test_tags = sorted(set(["ya:fat", "ya:external", "ya:noretries"] + ytest.get_values_list(unit, "TEST_TAGS_VALUE")))
  249. test_requirements = sorted(set(["network:full"] + ytest.get_values_list(unit, "TEST_REQUIREMENTS_VALUE")))
  250. test_record.update(
  251. {
  252. "SIZE": "LARGE",
  253. "TAG": ytest.serialize_list(test_tags),
  254. "REQUIREMENTS": ytest.serialize_list(test_requirements),
  255. "CONFIG-PATH": _resolve_config_path(unit, test_runner, rel_to="TS_TEST_FOR_PATH"),
  256. }
  257. )
  258. _add_test(unit, test_runner, test_files, deps, test_record)
  259. def _setup_eslint(unit):
  260. if not _is_tests_enabled(unit):
  261. return
  262. if unit.get("_NO_LINT_VALUE") == "none":
  263. return
  264. lint_files = ytest.get_values_list(unit, "_TS_LINT_SRCS_VALUE")
  265. if not lint_files:
  266. return
  267. unit.on_peerdir_ts_resource("eslint")
  268. mod_dir = unit.get("MODDIR")
  269. lint_files = _resolve_module_files(unit, mod_dir, lint_files)
  270. deps = _create_pm(unit).get_peers_from_package_json()
  271. test_record = {
  272. "ESLINT_CONFIG_PATH": _resolve_config_path(unit, "eslint", rel_to="MODDIR"),
  273. "LINT-FILE-PROCESSING-TIME": str(ESLINT_FILE_PROCESSING_TIME_DEFAULT),
  274. }
  275. _add_test(unit, "eslint", lint_files, deps, test_record, mod_dir)
  276. def _resolve_module_files(unit, mod_dir, file_paths):
  277. resolved_files = []
  278. for path in file_paths:
  279. resolved = rootrel_arc_src(path, unit)
  280. if resolved.startswith(mod_dir):
  281. mod_dir_with_sep_len = len(mod_dir) + 1
  282. resolved = resolved[mod_dir_with_sep_len:]
  283. resolved_files.append(resolved)
  284. return resolved_files
  285. def _add_test(unit, test_type, test_files, deps=None, test_record=None, test_cwd=None):
  286. from lib.nots.package_manager import constants
  287. def sort_uniq(text):
  288. return sorted(set(text))
  289. if deps:
  290. unit.ondepends(sort_uniq(deps))
  291. test_dir = get_norm_unit_path(unit)
  292. full_test_record = {
  293. "TEST-NAME": test_type.lower(),
  294. "TEST-TIMEOUT": unit.get("TEST_TIMEOUT") or "",
  295. "TEST-ENV": ytest.prepare_env(unit.get("TEST_ENV_VALUE")),
  296. "TESTED-PROJECT-NAME": os.path.splitext(unit.filename())[0],
  297. "TEST-RECIPES": ytest.prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  298. "SCRIPT-REL-PATH": test_type,
  299. "SOURCE-FOLDER-PATH": test_dir,
  300. "BUILD-FOLDER-PATH": test_dir,
  301. "BINARY-PATH": os.path.join(test_dir, unit.filename()),
  302. "SPLIT-FACTOR": unit.get("TEST_SPLIT_FACTOR") or "",
  303. "FORK-MODE": unit.get("TEST_FORK_MODE") or "",
  304. "SIZE": unit.get("TEST_SIZE_NAME") or "",
  305. "TEST-FILES": ytest.serialize_list(test_files),
  306. "TEST-CWD": test_cwd or "",
  307. "TAG": ytest.serialize_list(ytest.get_values_list(unit, "TEST_TAGS_VALUE")),
  308. "REQUIREMENTS": ytest.serialize_list(ytest.get_values_list(unit, "TEST_REQUIREMENTS_VALUE")),
  309. "NODEJS-ROOT-VAR-NAME": unit.get("NODEJS-ROOT-VAR-NAME"),
  310. "NODE-MODULES-BUNDLE-FILENAME": constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME,
  311. "CUSTOM-DEPENDENCIES": " ".join(sort_uniq((deps or []) + ytest.get_values_list(unit, "TEST_DEPENDS_VALUE"))),
  312. }
  313. if test_record:
  314. full_test_record.update(test_record)
  315. for k, v in full_test_record.items():
  316. if not isinstance(v, str):
  317. logger.warn(k, "expected 'str', got:", type(v))
  318. data = ytest.dump_test(unit, full_test_record)
  319. if data:
  320. unit.set_property(["DART_DATA", data])
  321. def _set_resource_vars(unit, erm_json, tool, version, nodejs_major=None):
  322. # type: (any, ErmJsonLite, Version, str|None, int|None) -> None
  323. resource_name = erm_json.canonize_name(tool).upper()
  324. # example: NODEJS_12_18_4 | HERMIONE_7_0_4_NODEJS_18
  325. version_str = str(version).replace(".", "_")
  326. yamake_resource_name = "{}_{}".format(resource_name, version_str)
  327. if erm_json.is_resource_multiplatform(tool):
  328. yamake_resource_name += "_NODEJS_{}".format(nodejs_major)
  329. yamake_resource_var = "{}_RESOURCE_GLOBAL".format(yamake_resource_name)
  330. unit.set(["{}_ROOT".format(resource_name), "${}".format(yamake_resource_var)])
  331. unit.set(["{}-ROOT-VAR-NAME".format(resource_name), yamake_resource_var])
  332. def _select_matching_version(erm_json, resource_name, range_str, dep_is_required=False):
  333. # type: (ErmJsonLite, str, str, bool) -> Version
  334. if dep_is_required and range_str is None:
  335. raise Exception(
  336. "Please install the '{tool}' package to the project. Run the command:\n"
  337. " ya tool nots add -D {tool}".format(tool=resource_name)
  338. )
  339. try:
  340. version = erm_json.select_version_of(resource_name, range_str)
  341. if version:
  342. return version
  343. raise ValueError("There is no allowed version to satisfy this range: '{}'".format(range_str))
  344. except Exception as error:
  345. toolchain_versions = erm_json.get_versions_of(erm_json.get_resource(resource_name))
  346. raise Exception(
  347. "Requested {} version range '{}' could not be satisfied. \n"
  348. "Please use a range that would include one of the following: {}. \n"
  349. "For further details please visit the link: {} \nOriginal error: {} \n".format(
  350. resource_name,
  351. range_str,
  352. ", ".join(map(str, toolchain_versions)),
  353. "https://docs.yandex-team.ru/ya-make/manual/typescript/toolchain",
  354. str(error),
  355. )
  356. )
  357. @_with_report_configure_error
  358. def on_node_modules_configure(unit):
  359. pm = _create_pm(unit)
  360. pj = pm.load_package_json_from_dir(pm.sources_path)
  361. if pj.has_dependencies():
  362. unit.onpeerdir(pm.get_local_peers_from_package_json())
  363. local_cli = unit.get("TS_LOCAL_CLI") == "yes"
  364. errors, ins, outs = pm.calc_node_modules_inouts(local_cli)
  365. if errors:
  366. ymake.report_configure_error(
  367. "There are some issues with lockfiles.\n"
  368. + "Please contact support (https://nda.ya.ru/t/sNoSFsO76ygSXL),\n"
  369. + "providing following details:\n"
  370. + "\n---\n".join([str(err) for err in errors])
  371. )
  372. else:
  373. unit.on_set_node_modules_ins_outs(["IN"] + sorted(ins) + ["OUT"] + sorted(outs))
  374. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  375. if not unit.get("TS_TEST_FOR"):
  376. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  377. if pj.get_use_prebuilder():
  378. lf = pm.load_lockfile_from_dir(pm.sources_path)
  379. is_valid, invalid_keys = lf.validate_has_addons_flags()
  380. if not is_valid:
  381. ymake.report_configure_error(
  382. "Project is configured to use @yatool/prebuilder. \n"
  383. + "Some packages in the pnpm-lock.yaml are misconfigured.\n"
  384. + "Run `ya tool nots update-lockfile` to fix lockfile.\n"
  385. + "All packages with `requiresBuild:true` have to be marked with `hasAddons:true/false`.\n"
  386. + "Misconfigured keys: \n"
  387. + " - "
  388. + "\n - ".join(invalid_keys)
  389. )
  390. unit.on_peerdir_ts_resource("@yatool/prebuilder")
  391. unit.set(
  392. [
  393. "_YATOOL_PREBUILDER_ARG",
  394. "--yatool-prebuilder-path $YATOOL_PREBUILDER_ROOT/node_modules/@yatool/prebuilder",
  395. ]
  396. )
  397. else:
  398. # default "noop" command
  399. unit.set(["_NODE_MODULES_CMD", "$TOUCH_UNIT"])
  400. @_with_report_configure_error
  401. def on_ts_test_for_configure(unit, test_runner, default_config, node_modules_filename):
  402. if not _is_tests_enabled(unit):
  403. return
  404. if unit.enabled('TS_COVERAGE'):
  405. unit.on_peerdir_ts_resource("nyc")
  406. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  407. unit.onpeerdir([for_mod_path])
  408. unit.on_setup_extract_node_modules_recipe([for_mod_path])
  409. unit.on_setup_extract_peer_tars_recipe([for_mod_path])
  410. root = "$B" if test_runner == "hermione" else "$(BUILD_ROOT)"
  411. unit.set(["TS_TEST_NM", os.path.join(root, for_mod_path, node_modules_filename)])
  412. config_path = unit.get("TS_TEST_CONFIG_PATH")
  413. if not config_path:
  414. config_path = os.path.join(for_mod_path, default_config)
  415. unit.set(["TS_TEST_CONFIG_PATH", config_path])
  416. test_record = _add_ts_resources_to_test_record(
  417. unit,
  418. {
  419. "TS-TEST-FOR-PATH": for_mod_path,
  420. "TS-TEST-DATA-DIRS": ytest.serialize_list(_get_ts_test_data_dirs(unit)),
  421. "TS-TEST-DATA-DIRS-RENAME": unit.get("_TS_TEST_DATA_DIRS_RENAME_VALUE"),
  422. },
  423. )
  424. test_files = ytest.get_values_list(unit, "_TS_TEST_SRCS_VALUE")
  425. test_files = _resolve_module_files(unit, unit.get("MODDIR"), test_files)
  426. if not test_files:
  427. ymake.report_configure_error("No tests found")
  428. return
  429. deps = _create_pm(unit).get_peers_from_package_json()
  430. add_ts_test = _get_test_runner_handlers()[test_runner]
  431. add_ts_test(unit, test_runner, test_files, deps, test_record)
  432. @_with_report_configure_error
  433. def on_validate_ts_test_for_args(unit, for_mod, root):
  434. # FBP-1085
  435. is_arc_root = root == "${ARCADIA_ROOT}"
  436. is_rel_for_mod = for_mod.startswith(".")
  437. if is_arc_root and is_rel_for_mod:
  438. ymake.report_configure_error(
  439. "You are using a relative path for a module. "
  440. + "You have to add RELATIVE key, like (RELATIVE {})".format(for_mod)
  441. )
  442. @_with_report_configure_error
  443. def on_set_ts_test_for_vars(unit, for_mod):
  444. unit.set(["TS_TEST_FOR", "yes"])
  445. unit.set(["TS_TEST_FOR_DIR", unit.resolve_arc_path(for_mod)])
  446. unit.set(["TS_TEST_FOR_PATH", rootrel_arc_src(for_mod, unit)])
  447. def _add_ts_resources_to_test_record(unit, test_record):
  448. erm_json = _create_erm_json(unit)
  449. for tool in erm_json.list_npm_packages():
  450. tool_resource_label = "{}-ROOT-VAR-NAME".format(tool.upper())
  451. tool_resource_value = unit.get(tool_resource_label)
  452. if tool_resource_value:
  453. test_record[tool_resource_label] = tool_resource_value
  454. return test_record
  455. @_with_report_configure_error
  456. def on_ts_files(unit, *files):
  457. new_cmds = ['$COPY_CMD ${{input;context=TEXT:"{0}"}} ${{output;noauto:"{0}"}}'.format(f) for f in files]
  458. all_cmds = unit.get("_TS_FILES_COPY_CMD")
  459. if all_cmds:
  460. new_cmds.insert(0, all_cmds)
  461. unit.set(["_TS_FILES_COPY_CMD", " && ".join(new_cmds)])
  462. @_with_report_configure_error
  463. def on_depends_on_mod(unit):
  464. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  465. unit.ondepends([for_mod_path])