nots.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. import os
  2. import typing
  3. from enum import auto, StrEnum
  4. import ymake
  5. import _dart_fields as df
  6. import ytest
  7. from _common import (
  8. rootrel_arc_src,
  9. sort_uniq,
  10. strip_roots,
  11. to_yesno,
  12. )
  13. from _dart_fields import create_dart_record
  14. # 1 is 60 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  15. # 0.5 is 120 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  16. # 0.2 is 300 files per chunk for TIMEOUT(60) - default timeout for SIZE(SMALL)
  17. ESLINT_FILE_PROCESSING_TIME_DEFAULT = 0.2 # seconds per file
  18. class TsTestType(StrEnum):
  19. JEST = auto()
  20. HERMIONE = auto()
  21. PLAYWRIGHT = auto()
  22. ESLINT = auto()
  23. TSC_TYPECHECK = auto()
  24. TS_STYLELINT = auto()
  25. TS_TEST_FIELDS_BASE = (
  26. df.BinaryPath.normalized,
  27. df.BuildFolderPath.normalized,
  28. df.ForkMode.test_fork_mode,
  29. df.NodejsRootVarName.value,
  30. df.ScriptRelPath.first_flat,
  31. df.SourceFolderPath.normalized,
  32. df.SplitFactor.from_unit,
  33. df.TestData.from_unit,
  34. df.TestedProjectName.filename_without_ext,
  35. df.TestEnv.value,
  36. df.TestName.value,
  37. df.TestRecipes.value,
  38. df.TestTimeout.from_unit,
  39. )
  40. TS_TEST_SPECIFIC_FIELDS = {
  41. TsTestType.JEST: (
  42. df.Size.from_unit,
  43. df.Tag.from_unit,
  44. df.Requirements.from_unit,
  45. df.ConfigPath.value,
  46. df.TsTestDataDirs.value,
  47. df.TsTestDataDirsRename.value,
  48. df.TsResources.value,
  49. df.TsTestForPath.value,
  50. ),
  51. TsTestType.HERMIONE: (
  52. df.Tag.from_unit_fat_external_no_retries,
  53. df.Requirements.from_unit_with_full_network,
  54. df.ConfigPath.value,
  55. df.TsTestDataDirs.value,
  56. df.TsTestDataDirsRename.value,
  57. df.TsResources.value,
  58. df.TsTestForPath.value,
  59. ),
  60. TsTestType.PLAYWRIGHT: (
  61. df.Size.from_unit,
  62. df.Tag.from_unit,
  63. df.Requirements.from_unit,
  64. df.ConfigPath.value,
  65. df.TsTestDataDirs.value,
  66. df.TsTestDataDirsRename.value,
  67. df.TsResources.value,
  68. df.TsTestForPath.value,
  69. ),
  70. TsTestType.ESLINT: (
  71. df.Size.from_unit,
  72. df.TestCwd.moddir,
  73. df.Tag.from_unit,
  74. df.Requirements.from_unit,
  75. df.EslintConfigPath.value,
  76. ),
  77. TsTestType.TSC_TYPECHECK: (
  78. df.Size.from_unit,
  79. df.TestCwd.moddir,
  80. df.Tag.from_unit,
  81. df.Requirements.from_unit,
  82. ),
  83. TsTestType.TS_STYLELINT: (
  84. df.TsStylelintConfig.value,
  85. df.TestFiles.stylesheets,
  86. df.NodeModulesBundleFilename.value,
  87. ),
  88. }
  89. class PluginLogger(object):
  90. def __init__(self):
  91. self.unit = None
  92. self.prefix = ""
  93. def reset(self, unit, prefix=""):
  94. self.unit = unit
  95. self.prefix = prefix
  96. def get_state(self):
  97. return (self.unit, self.prefix)
  98. def _stringify_messages(self, messages):
  99. parts = []
  100. for m in messages:
  101. if m is None:
  102. parts.append("None")
  103. else:
  104. parts.append(m if isinstance(m, str) else repr(m))
  105. # cyan color (code 36) for messages
  106. return "\033[0;32m{}\033[0;49m\n\033[0;36m{}\033[0;49m".format(self.prefix, " ".join(parts))
  107. def info(self, *messages):
  108. if self.unit:
  109. self.unit.message(["INFO", self._stringify_messages(messages)])
  110. def warn(self, *messages):
  111. if self.unit:
  112. self.unit.message(["WARN", self._stringify_messages(messages)])
  113. def error(self, *messages):
  114. if self.unit:
  115. self.unit.message(["ERROR", self._stringify_messages(messages)])
  116. def print_vars(self, *variables):
  117. if self.unit:
  118. values = ["{}={}".format(v, self.unit.get(v)) for v in variables]
  119. self.info("\n".join(values))
  120. logger = PluginLogger()
  121. def _with_report_configure_error(fn):
  122. def _wrapper(*args, **kwargs):
  123. last_state = logger.get_state()
  124. unit = args[0]
  125. logger.reset(unit if unit.get("TS_LOG") == "yes" else None, fn.__name__)
  126. try:
  127. fn(*args, **kwargs)
  128. except Exception as exc:
  129. ymake.report_configure_error(str(exc))
  130. if unit.get("TS_RAISE") == "yes":
  131. raise
  132. else:
  133. unit.message(["WARN", "Configure error is reported. Add -DTS_RAISE to see actual exception"])
  134. finally:
  135. logger.reset(*last_state)
  136. return _wrapper
  137. def _build_directives(name, flags, paths):
  138. # type: (str, list[str]|tuple[str], list[str]) -> str
  139. parts = [p for p in [name] + (flags or []) if p]
  140. parts_str = ";".join(parts)
  141. expressions = ['${{{parts}:"{path}"}}'.format(parts=parts_str, path=path) for path in paths]
  142. return " ".join(expressions)
  143. def _build_cmd_input_paths(paths, hide=False, disable_include_processor=False):
  144. # type: (list[str]|tuple[str], bool, bool) -> str
  145. hide_part = "hide" if hide else ""
  146. disable_ip_part = "context=TEXT" if disable_include_processor else ""
  147. return _build_directives("input", [hide_part, disable_ip_part], paths)
  148. def _create_erm_json(unit):
  149. from lib.nots.erm_json_lite import ErmJsonLite
  150. erm_packages_path = unit.get("ERM_PACKAGES_PATH")
  151. path = unit.resolve(unit.resolve_arc_path(erm_packages_path))
  152. return ErmJsonLite.load(path)
  153. def _get_pm_type(unit) -> typing.Literal["pnpm", "npm"]:
  154. resolved = unit.get("PM_TYPE")
  155. if not resolved:
  156. raise Exception("PM_TYPE is not set yet. Macro _SET_PACKAGE_MANAGER() should be called before.")
  157. return resolved
  158. def _get_source_path(unit):
  159. sources_path = unit.get("TS_TEST_FOR_DIR") if unit.get("TS_TEST_FOR") else unit.path()
  160. return sources_path
  161. def _create_pm(unit):
  162. from lib.nots.package_manager import get_package_manager_type
  163. sources_path = _get_source_path(unit)
  164. module_path = unit.get("TS_TEST_FOR_PATH") if unit.get("TS_TEST_FOR") else unit.get("MODDIR")
  165. # noinspection PyPep8Naming
  166. PackageManager = get_package_manager_type(_get_pm_type(unit))
  167. return PackageManager(
  168. sources_path=unit.resolve(sources_path),
  169. build_root="$B",
  170. build_path=unit.path().replace("$S", "$B", 1),
  171. contribs_path=unit.get("NPM_CONTRIBS_PATH"),
  172. nodejs_bin_path=None,
  173. script_path=None,
  174. module_path=module_path,
  175. )
  176. @_with_report_configure_error
  177. def on_set_package_manager(unit):
  178. pm_type = "pnpm" # projects without any lockfile are processed by pnpm
  179. source_path = _get_source_path(unit)
  180. for pm_key, lockfile_name in [("pnpm", "pnpm-lock.yaml"), ("npm", "package-lock.json")]:
  181. lf_path = os.path.join(source_path, lockfile_name)
  182. lf_path_resolved = unit.resolve_arc_path(strip_roots(lf_path))
  183. if lf_path_resolved:
  184. pm_type = pm_key
  185. break
  186. unit.on_peerdir_ts_resource(pm_type)
  187. unit.set(["PM_TYPE", pm_type])
  188. unit.set(["PM_SCRIPT", f"${pm_type.upper()}_SCRIPT"])
  189. @_with_report_configure_error
  190. def on_set_append_with_directive(unit, var_name, dir, *values):
  191. wrapped = ['${{{dir}:"{v}"}}'.format(dir=dir, v=v) for v in values]
  192. __set_append(unit, var_name, " ".join(wrapped))
  193. @_with_report_configure_error
  194. def on_from_npm_lockfiles(unit, *args):
  195. from lib.nots.package_manager.base import PackageManagerError
  196. # This is contrib with pnpm-lock.yaml files only
  197. # Force set to pnpm
  198. unit.set(["PM_TYPE", "pnpm"])
  199. pm = _create_pm(unit)
  200. lf_paths = []
  201. for lf_path in args:
  202. abs_lf_path = unit.resolve(unit.resolve_arc_path(lf_path))
  203. if abs_lf_path:
  204. lf_paths.append(abs_lf_path)
  205. elif unit.get("TS_STRICT_FROM_NPM_LOCKFILES") == "yes":
  206. ymake.report_configure_error("lockfile not found: {}".format(lf_path))
  207. try:
  208. for pkg in pm.extract_packages_meta_from_lockfiles(lf_paths):
  209. unit.on_from_npm([pkg.tarball_url, pkg.sky_id, pkg.integrity, pkg.integrity_algorithm, pkg.tarball_path])
  210. except PackageManagerError as e:
  211. logger.warn(str(e))
  212. pass
  213. def _check_nodejs_version(unit, major):
  214. if major < 14:
  215. raise Exception(
  216. "Node.js {} is unsupported. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major)
  217. )
  218. if major < 18:
  219. unit.message(
  220. [
  221. "WARN",
  222. "Node.js {} is deprecated. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major),
  223. ]
  224. )
  225. @_with_report_configure_error
  226. def on_peerdir_ts_resource(unit, *resources):
  227. from lib.nots.package_manager import BasePackageManager
  228. pj = BasePackageManager.load_package_json_from_dir(unit.resolve(_get_source_path(unit)))
  229. erm_json = _create_erm_json(unit)
  230. dirs = []
  231. nodejs_version = _select_matching_version(erm_json, "nodejs", pj.get_nodejs_version())
  232. _check_nodejs_version(unit, nodejs_version.major)
  233. for tool in resources:
  234. dir_name = erm_json.canonize_name(tool)
  235. if erm_json.use_resource_directly(tool):
  236. # raises the configuration error when the version is unsupported
  237. _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool), dep_is_required=True)
  238. elif tool == "nodejs":
  239. dirs.append(os.path.join("build", "platform", dir_name, str(nodejs_version)))
  240. _set_resource_vars(unit, erm_json, tool, nodejs_version)
  241. elif erm_json.is_resource_multiplatform(tool):
  242. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  243. sb_resources = [
  244. sbr for sbr in erm_json.get_sb_resources(tool, v) if sbr.get("nodejs") == nodejs_version.major
  245. ]
  246. nodejs_dir = "NODEJS_{}".format(nodejs_version.major)
  247. if len(sb_resources) > 0:
  248. dirs.append(os.path.join("build", "external_resources", dir_name, str(v), nodejs_dir))
  249. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  250. else:
  251. unit.message(["WARN", "Missing {}@{} for {}".format(tool, str(v), nodejs_dir)])
  252. else:
  253. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  254. dirs.append(os.path.join("build", "external_resources", dir_name, str(v)))
  255. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  256. if dirs:
  257. unit.onpeerdir(dirs)
  258. @_with_report_configure_error
  259. def on_ts_configure(unit):
  260. # type: (Unit) -> None
  261. from lib.nots.package_manager.base import PackageJson
  262. from lib.nots.package_manager.base.utils import build_pj_path
  263. from lib.nots.typescript import TsConfig
  264. tsconfig_paths = unit.get("TS_CONFIG_PATH").split()
  265. # for use in CMD as inputs
  266. __set_append(
  267. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(tsconfig_paths, hide=True, disable_include_processor=True)
  268. )
  269. mod_dir = unit.get("MODDIR")
  270. cur_dir = unit.get("TS_TEST_FOR_PATH") if unit.get("TS_TEST_FOR") else mod_dir
  271. pj_path = build_pj_path(unit.resolve(unit.resolve_arc_path(cur_dir)))
  272. dep_paths = PackageJson.load(pj_path).get_dep_paths_by_names()
  273. # reversed for using the first tsconfig as the config for include processor (legacy)
  274. for tsconfig_path in reversed(tsconfig_paths):
  275. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  276. if not abs_tsconfig_path:
  277. raise Exception("tsconfig not found: {}".format(tsconfig_path))
  278. tsconfig = TsConfig.load(abs_tsconfig_path)
  279. config_files = tsconfig.inline_extend(dep_paths)
  280. config_files = _resolve_module_files(unit, mod_dir, config_files)
  281. use_tsconfig_outdir = unit.get("TS_CONFIG_USE_OUTDIR") == "yes"
  282. tsconfig.validate(use_tsconfig_outdir)
  283. # add tsconfig files from which root tsconfig files were extended
  284. __set_append(
  285. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(config_files, hide=True, disable_include_processor=True)
  286. )
  287. # region include processor
  288. unit.set(["TS_CONFIG_ROOT_DIR", tsconfig.compiler_option("rootDir")]) # also for hermione
  289. if use_tsconfig_outdir:
  290. unit.set(["TS_CONFIG_OUT_DIR", tsconfig.compiler_option("outDir")]) # also for hermione
  291. unit.set(["TS_CONFIG_SOURCE_MAP", to_yesno(tsconfig.compiler_option("sourceMap"))])
  292. unit.set(["TS_CONFIG_DECLARATION", to_yesno(tsconfig.compiler_option("declaration"))])
  293. unit.set(["TS_CONFIG_DECLARATION_MAP", to_yesno(tsconfig.compiler_option("declarationMap"))])
  294. unit.set(["TS_CONFIG_PRESERVE_JSX", to_yesno(tsconfig.compiler_option("jsx") == "preserve")])
  295. # endregion
  296. _filter_inputs_by_rules_from_tsconfig(unit, tsconfig)
  297. # Code navigation
  298. if unit.get("TS_YNDEXING") == "yes":
  299. unit.on_do_ts_yndexing()
  300. # Style tests
  301. _setup_eslint(unit)
  302. _setup_tsc_typecheck(unit)
  303. _setup_stylelint(unit)
  304. @_with_report_configure_error
  305. def on_setup_build_env(unit): # type: (Unit) -> None
  306. build_env_var = unit.get("TS_BUILD_ENV") # type: str
  307. if not build_env_var:
  308. return
  309. options = []
  310. for name in build_env_var.split(","):
  311. options.append("--env")
  312. value = unit.get(f"TS_ENV_{name}")
  313. if value is None:
  314. ymake.report_configure_error(f"Env var '{name}' is provided in a list, but var value is not provided")
  315. continue
  316. double_quote_escaped_value = value.replace('"', '\\"')
  317. options.append(f'"{name}={double_quote_escaped_value}"')
  318. unit.set(["NOTS_TOOL_BUILD_ENV", " ".join(options)])
  319. def __set_append(unit, var_name, value):
  320. # type: (Unit, str, str|list[str]|tuple[str]) -> None
  321. """
  322. SET_APPEND() python naive implementation - append value/values to the list of values
  323. """
  324. previous_value = unit.get(var_name) or ""
  325. value_in_str = " ".join(value) if isinstance(value, list) or isinstance(value, tuple) else value
  326. new_value = previous_value + " " + value_in_str
  327. unit.set([var_name, new_value])
  328. def __strip_prefix(prefix, line):
  329. # type: (str, str) -> str
  330. if line.startswith(prefix):
  331. prefix_len = len(prefix)
  332. return line[prefix_len:]
  333. return line
  334. def _filter_inputs_by_rules_from_tsconfig(unit, tsconfig):
  335. """
  336. Reduce file list from the TS_GLOB_FILES variable following tsconfig.json rules
  337. """
  338. mod_dir = unit.get("MODDIR")
  339. target_path = os.path.join("${ARCADIA_ROOT}", mod_dir, "") # To have "/" in the end
  340. all_files = [__strip_prefix(target_path, f) for f in unit.get("TS_GLOB_FILES").split(" ")]
  341. filtered_files = tsconfig.filter_files(all_files)
  342. __set_append(unit, "TS_INPUT_FILES", [os.path.join(target_path, f) for f in filtered_files])
  343. def _is_tests_enabled(unit):
  344. if unit.get("TIDY") == "yes":
  345. return False
  346. return True
  347. def _setup_eslint(unit):
  348. if not _is_tests_enabled(unit):
  349. return
  350. if unit.get("_NO_LINT_VALUE") == "none":
  351. return
  352. test_files = df.TestFiles.ts_lint_srcs(unit, (), {})[df.TestFiles.KEY]
  353. if not test_files:
  354. return
  355. unit.on_peerdir_ts_resource("eslint")
  356. user_recipes = unit.get("TEST_RECIPES_VALUE")
  357. unit.on_setup_install_node_modules_recipe()
  358. test_type = TsTestType.ESLINT
  359. from lib.nots.package_manager import constants
  360. peers = _create_pm(unit).get_peers_from_package_json()
  361. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  362. if deps:
  363. joined_deps = "\n".join(deps)
  364. logger.info(f"{test_type} deps: \n{joined_deps}")
  365. unit.ondepends(deps)
  366. flat_args = (test_type, "MODDIR")
  367. dart_record = create_dart_record(
  368. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type],
  369. unit,
  370. flat_args,
  371. {},
  372. )
  373. dart_record[df.TestFiles.KEY] = test_files
  374. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  375. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  376. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  377. dart_record[df.LintFileProcessingTime.KEY] = str(ESLINT_FILE_PROCESSING_TIME_DEFAULT)
  378. data = ytest.dump_test(unit, dart_record)
  379. if data:
  380. unit.set_property(["DART_DATA", data])
  381. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  382. @_with_report_configure_error
  383. def _setup_tsc_typecheck(unit):
  384. if not _is_tests_enabled(unit):
  385. return
  386. if unit.get("_TS_TYPECHECK_VALUE") == "none":
  387. return
  388. test_files = df.TestFiles.ts_input_files(unit, (), {})[df.TestFiles.KEY]
  389. if not test_files:
  390. return
  391. tsconfig_paths = unit.get("TS_CONFIG_PATH").split()
  392. tsconfig_path = tsconfig_paths[0]
  393. if len(tsconfig_paths) > 1:
  394. tsconfig_path = unit.get("_TS_TYPECHECK_TSCONFIG")
  395. if not tsconfig_path:
  396. macros = " or ".join([f"TS_TYPECHECK({p})" for p in tsconfig_paths])
  397. raise Exception(f"Module uses several tsconfig files, specify which one to use for typecheck: {macros}")
  398. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  399. if not abs_tsconfig_path:
  400. raise Exception(f"tsconfig for typecheck not found: {tsconfig_path}")
  401. unit.on_peerdir_ts_resource("typescript")
  402. user_recipes = unit.get("TEST_RECIPES_VALUE")
  403. unit.on_setup_install_node_modules_recipe()
  404. unit.on_setup_extract_output_tars_recipe([unit.get("MODDIR")])
  405. test_type = TsTestType.TSC_TYPECHECK
  406. from lib.nots.package_manager import constants
  407. peers = _create_pm(unit).get_peers_from_package_json()
  408. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  409. if deps:
  410. joined_deps = "\n".join(deps)
  411. logger.info(f"{test_type} deps: \n{joined_deps}")
  412. unit.ondepends(deps)
  413. flat_args = (test_type,)
  414. dart_record = create_dart_record(
  415. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type],
  416. unit,
  417. flat_args,
  418. {},
  419. )
  420. dart_record[df.TestFiles.KEY] = test_files
  421. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  422. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  423. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  424. dart_record[df.TsConfigPath.KEY] = tsconfig_path
  425. data = ytest.dump_test(unit, dart_record)
  426. if data:
  427. unit.set_property(["DART_DATA", data])
  428. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  429. @_with_report_configure_error
  430. def _setup_stylelint(unit):
  431. if not _is_tests_enabled(unit):
  432. return
  433. if unit.get("_TS_STYLELINT_VALUE") == "no":
  434. return
  435. test_files = df.TestFiles.stylesheets(unit, (), {})[df.TestFiles.KEY]
  436. if not test_files:
  437. return
  438. from lib.nots.package_manager import constants
  439. recipes_value = unit.get("TEST_RECIPES_VALUE")
  440. unit.on_setup_install_node_modules_recipe()
  441. unit.on_setup_extract_output_tars_recipe([unit.get("MODDIR")])
  442. test_type = TsTestType.TS_STYLELINT
  443. peers = _create_pm(unit).get_peers_from_package_json()
  444. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  445. if deps:
  446. joined_deps = "\n".join(deps)
  447. logger.info(f"{test_type} deps: \n{joined_deps}")
  448. unit.ondepends(deps)
  449. flat_args = (test_type,)
  450. spec_args = dict(nm_bundle=constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME)
  451. dart_record = create_dart_record(
  452. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type], unit, flat_args, spec_args
  453. )
  454. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  455. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  456. data = ytest.dump_test(unit, dart_record)
  457. if data:
  458. unit.set_property(["DART_DATA", data])
  459. unit.set(["TEST_RECIPES_VALUE", recipes_value])
  460. def _resolve_module_files(unit, mod_dir, file_paths):
  461. mod_dir_with_sep_len = len(mod_dir) + 1
  462. resolved_files = []
  463. for path in file_paths:
  464. resolved = rootrel_arc_src(path, unit)
  465. if resolved.startswith(mod_dir):
  466. resolved = resolved[mod_dir_with_sep_len:]
  467. resolved_files.append(resolved)
  468. return resolved_files
  469. def _set_resource_vars(unit, erm_json, tool, version, nodejs_major=None):
  470. # type: (any, ErmJsonLite, Version, str|None, int|None) -> None
  471. resource_name = erm_json.canonize_name(tool).upper()
  472. # example: NODEJS_12_18_4 | HERMIONE_7_0_4_NODEJS_18
  473. version_str = str(version).replace(".", "_")
  474. yamake_resource_name = "{}_{}".format(resource_name, version_str)
  475. if erm_json.is_resource_multiplatform(tool):
  476. yamake_resource_name += "_NODEJS_{}".format(nodejs_major)
  477. yamake_resource_var = "{}_RESOURCE_GLOBAL".format(yamake_resource_name)
  478. unit.set(["{}_ROOT".format(resource_name), "${}".format(yamake_resource_var)])
  479. unit.set(["{}-ROOT-VAR-NAME".format(resource_name), yamake_resource_var])
  480. def _select_matching_version(erm_json, resource_name, range_str, dep_is_required=False):
  481. # type: (ErmJsonLite, str, str, bool) -> Version
  482. if dep_is_required and range_str is None:
  483. raise Exception(
  484. "Please install the '{tool}' package to the project. Run the command:\n"
  485. " ya tool nots add -D {tool}".format(tool=resource_name)
  486. )
  487. try:
  488. version = erm_json.select_version_of(resource_name, range_str)
  489. if version:
  490. return version
  491. raise ValueError("There is no allowed version to satisfy this range: '{}'".format(range_str))
  492. except Exception as error:
  493. toolchain_versions = erm_json.get_versions_of(erm_json.get_resource(resource_name))
  494. raise Exception(
  495. "Requested {} version range '{}' could not be satisfied. \n"
  496. "Please use a range that would include one of the following: {}. \n"
  497. "For further details please visit the link: {} \nOriginal error: {} \n".format(
  498. resource_name,
  499. range_str,
  500. ", ".join(map(str, toolchain_versions)),
  501. "https://docs.yandex-team.ru/frontend-in-arcadia/_generated/toolchain",
  502. str(error),
  503. )
  504. )
  505. @_with_report_configure_error
  506. def on_prepare_deps_configure(unit):
  507. contrib_path = unit.get("NPM_CONTRIBS_PATH")
  508. if contrib_path == '-':
  509. unit.on_prepare_deps_configure_no_contrib()
  510. return
  511. unit.onpeerdir(contrib_path)
  512. pm = _create_pm(unit)
  513. pj = pm.load_package_json_from_dir(pm.sources_path)
  514. has_deps = pj.has_dependencies()
  515. ins, outs = pm.calc_prepare_deps_inouts(unit.get("_TARBALLS_STORE"), has_deps)
  516. if has_deps:
  517. unit.onpeerdir(pm.get_local_peers_from_package_json())
  518. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  519. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  520. else:
  521. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", [], sorted(outs)))
  522. unit.set(["_PREPARE_DEPS_CMD", "$_PREPARE_NO_DEPS_CMD"])
  523. @_with_report_configure_error
  524. def on_prepare_deps_configure_no_contrib(unit):
  525. pm = _create_pm(unit)
  526. pj = pm.load_package_json_from_dir(pm.sources_path)
  527. has_deps = pj.has_dependencies()
  528. ins, outs, resources = pm.calc_prepare_deps_inouts_and_resources(unit.get("_TARBALLS_STORE"), has_deps)
  529. if has_deps:
  530. unit.onpeerdir(pm.get_local_peers_from_package_json())
  531. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  532. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  533. unit.set(["_PREPARE_DEPS_RESOURCES", " ".join([f'${{resource:"{uri}"}}' for uri in sorted(resources)])])
  534. unit.set(["_PREPARE_DEPS_USE_RESOURCES_FLAG", "--resource-root $(RESOURCE_ROOT)"])
  535. else:
  536. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", [], sorted(outs)))
  537. unit.set(["_PREPARE_DEPS_CMD", "$_PREPARE_NO_DEPS_CMD"])
  538. @_with_report_configure_error
  539. def on_node_modules_configure(unit):
  540. pm = _create_pm(unit)
  541. pj = pm.load_package_json_from_dir(pm.sources_path)
  542. if pj.has_dependencies():
  543. unit.onpeerdir(pm.get_local_peers_from_package_json())
  544. local_cli = unit.get("TS_LOCAL_CLI") == "yes"
  545. ins, outs = pm.calc_node_modules_inouts(local_cli)
  546. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  547. if not unit.get("TS_TEST_FOR"):
  548. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  549. if pj.get_use_prebuilder():
  550. unit.on_peerdir_ts_resource("@yatool/prebuilder")
  551. unit.set(
  552. [
  553. "_YATOOL_PREBUILDER_ARG",
  554. "--yatool-prebuilder-path $YATOOL_PREBUILDER_ROOT/node_modules/@yatool/prebuilder",
  555. ]
  556. )
  557. # YATOOL_PREBUILDER_0_7_0_RESOURCE_GLOBAL
  558. prebuilder_major = unit.get("YATOOL_PREBUILDER-ROOT-VAR-NAME").split("_")[2]
  559. logger.info(f"Detected prebuilder \033[0;32mv{prebuilder_major}.x.x\033[0;49m")
  560. if prebuilder_major == "0":
  561. # TODO: FBP-1408
  562. lf = pm.load_lockfile_from_dir(pm.sources_path)
  563. is_valid, invalid_keys = lf.validate_has_addons_flags()
  564. if not is_valid:
  565. ymake.report_configure_error(
  566. "Project is configured to use @yatool/prebuilder. \n"
  567. + "Some packages in the pnpm-lock.yaml are misconfigured.\n"
  568. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix lockfile.\n"
  569. + "All packages with `requiresBuild:true` have to be marked with `hasAddons:true/false`.\n"
  570. + "Misconfigured keys: \n"
  571. + " - "
  572. + "\n - ".join(invalid_keys)
  573. )
  574. else:
  575. lf = pm.load_lockfile_from_dir(pm.sources_path)
  576. requires_build_packages = lf.get_requires_build_packages()
  577. is_valid, validation_messages = pj.validate_prebuilds(requires_build_packages)
  578. if not is_valid:
  579. ymake.report_configure_error(
  580. "Project is configured to use @yatool/prebuilder. \n"
  581. + "Some packages are misconfigured.\n"
  582. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix pnpm-lock.yaml and package.json.\n"
  583. + "Validation details: \n"
  584. + "\n".join(validation_messages)
  585. )
  586. @_with_report_configure_error
  587. def on_ts_test_for_configure(unit, test_runner, default_config, node_modules_filename):
  588. if not _is_tests_enabled(unit):
  589. return
  590. if unit.enabled('TS_COVERAGE'):
  591. unit.on_peerdir_ts_resource("nyc")
  592. for_mod_path = df.TsTestForPath.value(unit, (), {})[df.TsTestForPath.KEY]
  593. unit.onpeerdir([for_mod_path])
  594. unit.on_setup_extract_node_modules_recipe([for_mod_path])
  595. unit.on_setup_extract_output_tars_recipe([for_mod_path])
  596. build_root = "$B" if test_runner == TsTestType.HERMIONE else "$(BUILD_ROOT)"
  597. unit.set(["TS_TEST_NM", os.path.join(build_root, for_mod_path, node_modules_filename)])
  598. config_path = unit.get("TS_TEST_CONFIG_PATH")
  599. if not config_path:
  600. config_path = os.path.join(for_mod_path, default_config)
  601. unit.set(["TS_TEST_CONFIG_PATH", config_path])
  602. test_files = df.TestFiles.ts_test_srcs(unit, (), {})[df.TestFiles.KEY]
  603. if not test_files:
  604. ymake.report_configure_error("No tests found")
  605. return
  606. from lib.nots.package_manager import constants
  607. peers = _create_pm(unit).get_peers_from_package_json()
  608. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  609. if deps:
  610. joined_deps = "\n".join(deps)
  611. logger.info(f"{test_runner} deps: \n{joined_deps}")
  612. unit.ondepends(deps)
  613. flat_args = (test_runner, "TS_TEST_FOR_PATH")
  614. spec_args = {'erm_json': _create_erm_json(unit)}
  615. dart_record = create_dart_record(
  616. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_runner],
  617. unit,
  618. flat_args,
  619. spec_args,
  620. )
  621. dart_record[df.TestFiles.KEY] = test_files
  622. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  623. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  624. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  625. if test_runner == TsTestType.HERMIONE:
  626. dart_record[df.Size.KEY] = "LARGE"
  627. data = ytest.dump_test(unit, dart_record)
  628. if data:
  629. unit.set_property(["DART_DATA", data])
  630. @_with_report_configure_error
  631. def on_validate_ts_test_for_args(unit, for_mod, root):
  632. # FBP-1085
  633. is_arc_root = root == "${ARCADIA_ROOT}"
  634. is_rel_for_mod = for_mod.startswith(".")
  635. if is_arc_root and is_rel_for_mod:
  636. ymake.report_configure_error(
  637. "You are using a relative path for a module. "
  638. + "You have to add RELATIVE key, like (RELATIVE {})".format(for_mod)
  639. )
  640. @_with_report_configure_error
  641. def on_set_ts_test_for_vars(unit, for_mod):
  642. unit.set(["TS_TEST_FOR", "yes"])
  643. unit.set(["TS_TEST_FOR_DIR", unit.resolve_arc_path(for_mod)])
  644. unit.set(["TS_TEST_FOR_PATH", rootrel_arc_src(for_mod, unit)])
  645. @_with_report_configure_error
  646. def on_ts_files(unit, *files):
  647. new_cmds = ['$COPY_CMD ${{input;context=TEXT:"{0}"}} ${{output;noauto:"{0}"}}'.format(f) for f in files]
  648. all_cmds = unit.get("_TS_FILES_COPY_CMD")
  649. if all_cmds:
  650. new_cmds.insert(0, all_cmds)
  651. unit.set(["_TS_FILES_COPY_CMD", " && ".join(new_cmds)])
  652. @_with_report_configure_error
  653. def on_ts_package_check_files(unit):
  654. ts_files = unit.get("_TS_FILES_COPY_CMD")
  655. if ts_files == "":
  656. ymake.report_configure_error(
  657. "\n"
  658. "In the TS_PACKAGE module, you should define at least one file using the TS_FILES() macro.\n"
  659. "Docs: https://docs.yandex-team.ru/frontend-in-arcadia/references/TS_PACKAGE#ts-files."
  660. )
  661. @_with_report_configure_error
  662. def on_depends_on_mod(unit):
  663. if unit.get("_TS_TEST_DEPENDS_ON_BUILD"):
  664. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  665. unit.ondepends([for_mod_path])