nots.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. if pm_type == 'npm' and "devtools/dummy_arcadia/typescript/npm" not in source_path:
  187. ymake.report_configure_error(
  188. "\n"
  189. "Project is configured to use npm as a package manager. \n"
  190. "Only pnpm is supported at the moment.\n"
  191. "Please follow the instruction to migrate your project:\n"
  192. "https://docs.yandex-team.ru/frontend-in-arcadia/tutorials/migrate#migrate-to-pnpm"
  193. )
  194. unit.on_peerdir_ts_resource(pm_type)
  195. unit.set(["PM_TYPE", pm_type])
  196. unit.set(["PM_SCRIPT", f"${pm_type.upper()}_SCRIPT"])
  197. @_with_report_configure_error
  198. def on_set_append_with_directive(unit, var_name, dir, *values):
  199. wrapped = ['${{{dir}:"{v}"}}'.format(dir=dir, v=v) for v in values]
  200. __set_append(unit, var_name, " ".join(wrapped))
  201. @_with_report_configure_error
  202. def on_from_npm_lockfiles(unit, *args):
  203. from lib.nots.package_manager.base import PackageManagerError
  204. # This is contrib with pnpm-lock.yaml files only
  205. # Force set to pnpm
  206. unit.set(["PM_TYPE", "pnpm"])
  207. pm = _create_pm(unit)
  208. lf_paths = []
  209. for lf_path in args:
  210. abs_lf_path = unit.resolve(unit.resolve_arc_path(lf_path))
  211. if abs_lf_path:
  212. lf_paths.append(abs_lf_path)
  213. elif unit.get("TS_STRICT_FROM_NPM_LOCKFILES") == "yes":
  214. ymake.report_configure_error("lockfile not found: {}".format(lf_path))
  215. try:
  216. for pkg in pm.extract_packages_meta_from_lockfiles(lf_paths):
  217. unit.on_from_npm([pkg.tarball_url, pkg.sky_id, pkg.integrity, pkg.integrity_algorithm, pkg.tarball_path])
  218. except PackageManagerError as e:
  219. logger.warn(str(e))
  220. pass
  221. def _check_nodejs_version(unit, major):
  222. if major < 14:
  223. raise Exception(
  224. "Node.js {} is unsupported. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major)
  225. )
  226. if major < 18:
  227. unit.message(
  228. [
  229. "WARN",
  230. "Node.js {} is deprecated. Update Node.js please. See https://nda.ya.ru/t/joB9Mivm6h4znu".format(major),
  231. ]
  232. )
  233. @_with_report_configure_error
  234. def on_peerdir_ts_resource(unit, *resources):
  235. from lib.nots.package_manager import BasePackageManager
  236. pj = BasePackageManager.load_package_json_from_dir(unit.resolve(_get_source_path(unit)))
  237. erm_json = _create_erm_json(unit)
  238. dirs = []
  239. nodejs_version = _select_matching_version(erm_json, "nodejs", pj.get_nodejs_version())
  240. _check_nodejs_version(unit, nodejs_version.major)
  241. for tool in resources:
  242. dir_name = erm_json.canonize_name(tool)
  243. if erm_json.use_resource_directly(tool):
  244. # raises the configuration error when the version is unsupported
  245. _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool), dep_is_required=True)
  246. elif tool == "nodejs":
  247. dirs.append(os.path.join("build", "platform", dir_name, str(nodejs_version)))
  248. _set_resource_vars(unit, erm_json, tool, nodejs_version)
  249. elif erm_json.is_resource_multiplatform(tool):
  250. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  251. sb_resources = [
  252. sbr for sbr in erm_json.get_sb_resources(tool, v) if sbr.get("nodejs") == nodejs_version.major
  253. ]
  254. nodejs_dir = "NODEJS_{}".format(nodejs_version.major)
  255. if len(sb_resources) > 0:
  256. dirs.append(os.path.join("build", "external_resources", dir_name, str(v), nodejs_dir))
  257. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  258. else:
  259. unit.message(["WARN", "Missing {}@{} for {}".format(tool, str(v), nodejs_dir)])
  260. else:
  261. v = _select_matching_version(erm_json, tool, pj.get_dep_specifier(tool))
  262. dirs.append(os.path.join("build", "external_resources", dir_name, str(v)))
  263. _set_resource_vars(unit, erm_json, tool, v, nodejs_version.major)
  264. if dirs:
  265. unit.onpeerdir(dirs)
  266. @_with_report_configure_error
  267. def on_ts_configure(unit):
  268. # type: (Unit) -> None
  269. from lib.nots.package_manager.base import PackageJson
  270. from lib.nots.package_manager.base.utils import build_pj_path
  271. from lib.nots.typescript import TsConfig
  272. tsconfig_paths = unit.get("TS_CONFIG_PATH").split()
  273. # for use in CMD as inputs
  274. __set_append(
  275. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(tsconfig_paths, hide=True, disable_include_processor=True)
  276. )
  277. mod_dir = unit.get("MODDIR")
  278. cur_dir = unit.get("TS_TEST_FOR_PATH") if unit.get("TS_TEST_FOR") else mod_dir
  279. pj_path = build_pj_path(unit.resolve(unit.resolve_arc_path(cur_dir)))
  280. dep_paths = PackageJson.load(pj_path).get_dep_paths_by_names()
  281. # reversed for using the first tsconfig as the config for include processor (legacy)
  282. for tsconfig_path in reversed(tsconfig_paths):
  283. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  284. if not abs_tsconfig_path:
  285. raise Exception("tsconfig not found: {}".format(tsconfig_path))
  286. tsconfig = TsConfig.load(abs_tsconfig_path)
  287. config_files = tsconfig.inline_extend(dep_paths)
  288. config_files = _resolve_module_files(unit, mod_dir, config_files)
  289. use_tsconfig_outdir = unit.get("TS_CONFIG_USE_OUTDIR") == "yes"
  290. tsconfig.validate(use_tsconfig_outdir)
  291. # add tsconfig files from which root tsconfig files were extended
  292. __set_append(
  293. unit, "TS_CONFIG_FILES", _build_cmd_input_paths(config_files, hide=True, disable_include_processor=True)
  294. )
  295. # region include processor
  296. unit.set(["TS_CONFIG_ROOT_DIR", tsconfig.compiler_option("rootDir")]) # also for hermione
  297. if use_tsconfig_outdir:
  298. unit.set(["TS_CONFIG_OUT_DIR", tsconfig.compiler_option("outDir")]) # also for hermione
  299. unit.set(["TS_CONFIG_SOURCE_MAP", to_yesno(tsconfig.compiler_option("sourceMap"))])
  300. unit.set(["TS_CONFIG_DECLARATION", to_yesno(tsconfig.compiler_option("declaration"))])
  301. unit.set(["TS_CONFIG_DECLARATION_MAP", to_yesno(tsconfig.compiler_option("declarationMap"))])
  302. unit.set(["TS_CONFIG_PRESERVE_JSX", to_yesno(tsconfig.compiler_option("jsx") == "preserve")])
  303. # endregion
  304. _filter_inputs_by_rules_from_tsconfig(unit, tsconfig)
  305. # Code navigation
  306. if unit.get("TS_YNDEXING") == "yes":
  307. unit.on_do_ts_yndexing()
  308. # Style tests
  309. _setup_eslint(unit)
  310. _setup_tsc_typecheck(unit)
  311. _setup_stylelint(unit)
  312. @_with_report_configure_error
  313. def on_setup_build_env(unit): # type: (Unit) -> None
  314. build_env_var = unit.get("TS_BUILD_ENV") # type: str
  315. if not build_env_var:
  316. return
  317. options = []
  318. for name in build_env_var.split(","):
  319. options.append("--env")
  320. value = unit.get(f"TS_ENV_{name}")
  321. if value is None:
  322. ymake.report_configure_error(f"Env var '{name}' is provided in a list, but var value is not provided")
  323. continue
  324. double_quote_escaped_value = value.replace('"', '\\"')
  325. options.append(f'"{name}={double_quote_escaped_value}"')
  326. unit.set(["NOTS_TOOL_BUILD_ENV", " ".join(options)])
  327. def __set_append(unit, var_name, value):
  328. # type: (Unit, str, str|list[str]|tuple[str]) -> None
  329. """
  330. SET_APPEND() python naive implementation - append value/values to the list of values
  331. """
  332. previous_value = unit.get(var_name) or ""
  333. value_in_str = " ".join(value) if isinstance(value, list) or isinstance(value, tuple) else value
  334. new_value = previous_value + " " + value_in_str
  335. unit.set([var_name, new_value])
  336. def __strip_prefix(prefix, line):
  337. # type: (str, str) -> str
  338. if line.startswith(prefix):
  339. prefix_len = len(prefix)
  340. return line[prefix_len:]
  341. return line
  342. def _filter_inputs_by_rules_from_tsconfig(unit, tsconfig):
  343. """
  344. Reduce file list from the TS_GLOB_FILES variable following tsconfig.json rules
  345. """
  346. mod_dir = unit.get("MODDIR")
  347. target_path = os.path.join("${ARCADIA_ROOT}", mod_dir, "") # To have "/" in the end
  348. all_files = [__strip_prefix(target_path, f) for f in unit.get("TS_GLOB_FILES").split(" ")]
  349. filtered_files = tsconfig.filter_files(all_files)
  350. __set_append(unit, "TS_INPUT_FILES", [os.path.join(target_path, f) for f in filtered_files])
  351. def _is_tests_enabled(unit):
  352. if unit.get("TIDY") == "yes":
  353. return False
  354. return True
  355. def _setup_eslint(unit):
  356. if not _is_tests_enabled(unit):
  357. return
  358. if unit.get("_NO_LINT_VALUE") == "none":
  359. return
  360. test_files = df.TestFiles.ts_lint_srcs(unit, (), {})[df.TestFiles.KEY]
  361. if not test_files:
  362. return
  363. unit.on_peerdir_ts_resource("eslint")
  364. user_recipes = unit.get("TEST_RECIPES_VALUE")
  365. unit.on_setup_install_node_modules_recipe()
  366. test_type = TsTestType.ESLINT
  367. from lib.nots.package_manager import constants
  368. peers = _create_pm(unit).get_peers_from_package_json()
  369. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  370. if deps:
  371. joined_deps = "\n".join(deps)
  372. logger.info(f"{test_type} deps: \n{joined_deps}")
  373. unit.ondepends(deps)
  374. flat_args = (test_type, "MODDIR")
  375. dart_record = create_dart_record(
  376. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type],
  377. unit,
  378. flat_args,
  379. {},
  380. )
  381. dart_record[df.TestFiles.KEY] = test_files
  382. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  383. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  384. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  385. dart_record[df.LintFileProcessingTime.KEY] = str(ESLINT_FILE_PROCESSING_TIME_DEFAULT)
  386. data = ytest.dump_test(unit, dart_record)
  387. if data:
  388. unit.set_property(["DART_DATA", data])
  389. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  390. @_with_report_configure_error
  391. def _setup_tsc_typecheck(unit):
  392. if not _is_tests_enabled(unit):
  393. return
  394. if unit.get("_TS_TYPECHECK_VALUE") == "none":
  395. return
  396. test_files = df.TestFiles.ts_input_files(unit, (), {})[df.TestFiles.KEY]
  397. if not test_files:
  398. return
  399. tsconfig_paths = unit.get("TS_CONFIG_PATH").split()
  400. tsconfig_path = tsconfig_paths[0]
  401. if len(tsconfig_paths) > 1:
  402. tsconfig_path = unit.get("_TS_TYPECHECK_TSCONFIG")
  403. if not tsconfig_path:
  404. macros = " or ".join([f"TS_TYPECHECK({p})" for p in tsconfig_paths])
  405. raise Exception(f"Module uses several tsconfig files, specify which one to use for typecheck: {macros}")
  406. abs_tsconfig_path = unit.resolve(unit.resolve_arc_path(tsconfig_path))
  407. if not abs_tsconfig_path:
  408. raise Exception(f"tsconfig for typecheck not found: {tsconfig_path}")
  409. unit.on_peerdir_ts_resource("typescript")
  410. user_recipes = unit.get("TEST_RECIPES_VALUE")
  411. unit.on_setup_install_node_modules_recipe()
  412. unit.on_setup_extract_output_tars_recipe([unit.get("MODDIR")])
  413. test_type = TsTestType.TSC_TYPECHECK
  414. from lib.nots.package_manager import constants
  415. peers = _create_pm(unit).get_peers_from_package_json()
  416. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  417. if deps:
  418. joined_deps = "\n".join(deps)
  419. logger.info(f"{test_type} deps: \n{joined_deps}")
  420. unit.ondepends(deps)
  421. flat_args = (test_type,)
  422. dart_record = create_dart_record(
  423. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type],
  424. unit,
  425. flat_args,
  426. {},
  427. )
  428. dart_record[df.TestFiles.KEY] = test_files
  429. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  430. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  431. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  432. dart_record[df.TsConfigPath.KEY] = tsconfig_path
  433. data = ytest.dump_test(unit, dart_record)
  434. if data:
  435. unit.set_property(["DART_DATA", data])
  436. unit.set(["TEST_RECIPES_VALUE", user_recipes])
  437. @_with_report_configure_error
  438. def _setup_stylelint(unit):
  439. if not _is_tests_enabled(unit):
  440. return
  441. if unit.get("_TS_STYLELINT_VALUE") == "no":
  442. return
  443. test_files = df.TestFiles.stylesheets(unit, (), {})[df.TestFiles.KEY]
  444. if not test_files:
  445. return
  446. from lib.nots.package_manager import constants
  447. recipes_value = unit.get("TEST_RECIPES_VALUE")
  448. unit.on_setup_install_node_modules_recipe()
  449. unit.on_setup_extract_output_tars_recipe([unit.get("MODDIR")])
  450. test_type = TsTestType.TS_STYLELINT
  451. peers = _create_pm(unit).get_peers_from_package_json()
  452. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  453. if deps:
  454. joined_deps = "\n".join(deps)
  455. logger.info(f"{test_type} deps: \n{joined_deps}")
  456. unit.ondepends(deps)
  457. flat_args = (test_type,)
  458. spec_args = dict(nm_bundle=constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME)
  459. dart_record = create_dart_record(
  460. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_type], unit, flat_args, spec_args
  461. )
  462. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  463. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  464. data = ytest.dump_test(unit, dart_record)
  465. if data:
  466. unit.set_property(["DART_DATA", data])
  467. unit.set(["TEST_RECIPES_VALUE", recipes_value])
  468. def _resolve_module_files(unit, mod_dir, file_paths):
  469. mod_dir_with_sep_len = len(mod_dir) + 1
  470. resolved_files = []
  471. for path in file_paths:
  472. resolved = rootrel_arc_src(path, unit)
  473. if resolved.startswith(mod_dir):
  474. resolved = resolved[mod_dir_with_sep_len:]
  475. resolved_files.append(resolved)
  476. return resolved_files
  477. def _set_resource_vars(unit, erm_json, tool, version, nodejs_major=None):
  478. # type: (any, ErmJsonLite, Version, str|None, int|None) -> None
  479. resource_name = erm_json.canonize_name(tool).upper()
  480. # example: NODEJS_12_18_4 | HERMIONE_7_0_4_NODEJS_18
  481. version_str = str(version).replace(".", "_")
  482. yamake_resource_name = "{}_{}".format(resource_name, version_str)
  483. if erm_json.is_resource_multiplatform(tool):
  484. yamake_resource_name += "_NODEJS_{}".format(nodejs_major)
  485. yamake_resource_var = "{}_RESOURCE_GLOBAL".format(yamake_resource_name)
  486. unit.set(["{}_ROOT".format(resource_name), "${}".format(yamake_resource_var)])
  487. unit.set(["{}-ROOT-VAR-NAME".format(resource_name), yamake_resource_var])
  488. def _select_matching_version(erm_json, resource_name, range_str, dep_is_required=False):
  489. # type: (ErmJsonLite, str, str, bool) -> Version
  490. if dep_is_required and range_str is None:
  491. raise Exception(
  492. "Please install the '{tool}' package to the project. Run the command:\n"
  493. " ya tool nots add -D {tool}".format(tool=resource_name)
  494. )
  495. try:
  496. version = erm_json.select_version_of(resource_name, range_str)
  497. if version:
  498. return version
  499. raise ValueError("There is no allowed version to satisfy this range: '{}'".format(range_str))
  500. except Exception as error:
  501. toolchain_versions = erm_json.get_versions_of(erm_json.get_resource(resource_name))
  502. raise Exception(
  503. "Requested {} version range '{}' could not be satisfied. \n"
  504. "Please use a range that would include one of the following: {}. \n"
  505. "For further details please visit the link: {} \nOriginal error: {} \n".format(
  506. resource_name,
  507. range_str,
  508. ", ".join(map(str, toolchain_versions)),
  509. "https://docs.yandex-team.ru/frontend-in-arcadia/_generated/toolchain",
  510. str(error),
  511. )
  512. )
  513. @_with_report_configure_error
  514. def on_prepare_deps_configure(unit):
  515. contrib_path = unit.get("NPM_CONTRIBS_PATH")
  516. if contrib_path == '-':
  517. unit.on_prepare_deps_configure_no_contrib()
  518. return
  519. unit.onpeerdir(contrib_path)
  520. pm = _create_pm(unit)
  521. pj = pm.load_package_json_from_dir(pm.sources_path)
  522. has_deps = pj.has_dependencies()
  523. ins, outs = pm.calc_prepare_deps_inouts(unit.get("_TARBALLS_STORE"), has_deps)
  524. if has_deps:
  525. unit.onpeerdir(pm.get_local_peers_from_package_json())
  526. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  527. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  528. else:
  529. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", [], sorted(outs)))
  530. unit.set(["_PREPARE_DEPS_CMD", "$_PREPARE_NO_DEPS_CMD"])
  531. @_with_report_configure_error
  532. def on_prepare_deps_configure_no_contrib(unit):
  533. pm = _create_pm(unit)
  534. pj = pm.load_package_json_from_dir(pm.sources_path)
  535. has_deps = pj.has_dependencies()
  536. ins, outs, resources = pm.calc_prepare_deps_inouts_and_resources(unit.get("_TARBALLS_STORE"), has_deps)
  537. if has_deps:
  538. unit.onpeerdir(pm.get_local_peers_from_package_json())
  539. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  540. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  541. unit.set(["_PREPARE_DEPS_RESOURCES", " ".join([f'${{resource:"{uri}"}}' for uri in sorted(resources)])])
  542. unit.set(["_PREPARE_DEPS_USE_RESOURCES_FLAG", "--resource-root $(RESOURCE_ROOT)"])
  543. else:
  544. __set_append(unit, "_PREPARE_DEPS_INOUTS", _build_directives("output", [], sorted(outs)))
  545. unit.set(["_PREPARE_DEPS_CMD", "$_PREPARE_NO_DEPS_CMD"])
  546. @_with_report_configure_error
  547. def on_node_modules_configure(unit):
  548. pm = _create_pm(unit)
  549. pj = pm.load_package_json_from_dir(pm.sources_path)
  550. if pj.has_dependencies():
  551. unit.onpeerdir(pm.get_local_peers_from_package_json())
  552. local_cli = unit.get("TS_LOCAL_CLI") == "yes"
  553. ins, outs = pm.calc_node_modules_inouts(local_cli)
  554. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("input", ["hide"], sorted(ins)))
  555. if not unit.get("TS_TEST_FOR"):
  556. __set_append(unit, "_NODE_MODULES_INOUTS", _build_directives("output", ["hide"], sorted(outs)))
  557. if pj.get_use_prebuilder():
  558. unit.on_peerdir_ts_resource("@yatool/prebuilder")
  559. unit.set(
  560. [
  561. "_YATOOL_PREBUILDER_ARG",
  562. "--yatool-prebuilder-path $YATOOL_PREBUILDER_ROOT/node_modules/@yatool/prebuilder",
  563. ]
  564. )
  565. # YATOOL_PREBUILDER_0_7_0_RESOURCE_GLOBAL
  566. prebuilder_major = unit.get("YATOOL_PREBUILDER-ROOT-VAR-NAME").split("_")[2]
  567. logger.info(f"Detected prebuilder \033[0;32mv{prebuilder_major}.x.x\033[0;49m")
  568. if prebuilder_major == "0":
  569. # TODO: FBP-1408
  570. lf = pm.load_lockfile_from_dir(pm.sources_path)
  571. is_valid, invalid_keys = lf.validate_has_addons_flags()
  572. if not is_valid:
  573. ymake.report_configure_error(
  574. "Project is configured to use @yatool/prebuilder. \n"
  575. + "Some packages in the pnpm-lock.yaml are misconfigured.\n"
  576. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix lockfile.\n"
  577. + "All packages with `requiresBuild:true` have to be marked with `hasAddons:true/false`.\n"
  578. + "Misconfigured keys: \n"
  579. + " - "
  580. + "\n - ".join(invalid_keys)
  581. )
  582. else:
  583. lf = pm.load_lockfile_from_dir(pm.sources_path)
  584. requires_build_packages = lf.get_requires_build_packages()
  585. is_valid, validation_messages = pj.validate_prebuilds(requires_build_packages)
  586. if not is_valid:
  587. ymake.report_configure_error(
  588. "Project is configured to use @yatool/prebuilder. \n"
  589. + "Some packages are misconfigured.\n"
  590. + "Run \033[0;32m`ya tool nots update-lockfile`\033[0;49m to fix pnpm-lock.yaml and package.json.\n"
  591. + "Validation details: \n"
  592. + "\n".join(validation_messages)
  593. )
  594. @_with_report_configure_error
  595. def on_ts_test_for_configure(unit, test_runner, default_config, node_modules_filename):
  596. if not _is_tests_enabled(unit):
  597. return
  598. if unit.enabled('TS_COVERAGE'):
  599. unit.on_peerdir_ts_resource("nyc")
  600. for_mod_path = df.TsTestForPath.value(unit, (), {})[df.TsTestForPath.KEY]
  601. unit.onpeerdir([for_mod_path])
  602. unit.on_setup_extract_node_modules_recipe([for_mod_path])
  603. unit.on_setup_extract_output_tars_recipe([for_mod_path])
  604. build_root = "$B" if test_runner == TsTestType.HERMIONE else "$(BUILD_ROOT)"
  605. unit.set(["TS_TEST_NM", os.path.join(build_root, for_mod_path, node_modules_filename)])
  606. config_path = unit.get("TS_TEST_CONFIG_PATH")
  607. if not config_path:
  608. config_path = os.path.join(for_mod_path, default_config)
  609. unit.set(["TS_TEST_CONFIG_PATH", config_path])
  610. test_files = df.TestFiles.ts_test_srcs(unit, (), {})[df.TestFiles.KEY]
  611. if not test_files:
  612. ymake.report_configure_error("No tests found")
  613. return
  614. from lib.nots.package_manager import constants
  615. peers = _create_pm(unit).get_peers_from_package_json()
  616. deps = df.CustomDependencies.nots_with_recipies(unit, (peers,), {})[df.CustomDependencies.KEY].split()
  617. if deps:
  618. joined_deps = "\n".join(deps)
  619. logger.info(f"{test_runner} deps: \n{joined_deps}")
  620. unit.ondepends(deps)
  621. flat_args = (test_runner, "TS_TEST_FOR_PATH")
  622. spec_args = {'erm_json': _create_erm_json(unit)}
  623. dart_record = create_dart_record(
  624. TS_TEST_FIELDS_BASE + TS_TEST_SPECIFIC_FIELDS[test_runner],
  625. unit,
  626. flat_args,
  627. spec_args,
  628. )
  629. dart_record[df.TestFiles.KEY] = test_files
  630. dart_record[df.NodeModulesBundleFilename.KEY] = constants.NODE_MODULES_WORKSPACE_BUNDLE_FILENAME
  631. extra_deps = df.CustomDependencies.test_depends_only(unit, (), {})[df.CustomDependencies.KEY].split()
  632. dart_record[df.CustomDependencies.KEY] = " ".join(sort_uniq(deps + extra_deps))
  633. if test_runner == TsTestType.HERMIONE:
  634. dart_record[df.Size.KEY] = "LARGE"
  635. data = ytest.dump_test(unit, dart_record)
  636. if data:
  637. unit.set_property(["DART_DATA", data])
  638. @_with_report_configure_error
  639. def on_validate_ts_test_for_args(unit, for_mod, root):
  640. # FBP-1085
  641. is_arc_root = root == "${ARCADIA_ROOT}"
  642. is_rel_for_mod = for_mod.startswith(".")
  643. if is_arc_root and is_rel_for_mod:
  644. ymake.report_configure_error(
  645. "You are using a relative path for a module. "
  646. + "You have to add RELATIVE key, like (RELATIVE {})".format(for_mod)
  647. )
  648. @_with_report_configure_error
  649. def on_set_ts_test_for_vars(unit, for_mod):
  650. unit.set(["TS_TEST_FOR", "yes"])
  651. unit.set(["TS_TEST_FOR_DIR", unit.resolve_arc_path(for_mod)])
  652. unit.set(["TS_TEST_FOR_PATH", rootrel_arc_src(for_mod, unit)])
  653. @_with_report_configure_error
  654. def on_ts_files(unit, *files):
  655. new_cmds = ['$COPY_CMD ${{input;context=TEXT:"{0}"}} ${{output;noauto:"{0}"}}'.format(f) for f in files]
  656. all_cmds = unit.get("_TS_FILES_COPY_CMD")
  657. if all_cmds:
  658. new_cmds.insert(0, all_cmds)
  659. unit.set(["_TS_FILES_COPY_CMD", " && ".join(new_cmds)])
  660. @_with_report_configure_error
  661. def on_ts_package_check_files(unit):
  662. ts_files = unit.get("_TS_FILES_COPY_CMD")
  663. if ts_files == "":
  664. ymake.report_configure_error(
  665. "\n"
  666. "In the TS_PACKAGE module, you should define at least one file using the TS_FILES() macro.\n"
  667. "If you use the TS_FILES_GLOB, check the expression. For example, use `src/**/*` instead of `src/*`.\n"
  668. "Docs: https://docs.yandex-team.ru/frontend-in-arcadia/references/TS_PACKAGE#ts-files."
  669. )
  670. @_with_report_configure_error
  671. def on_depends_on_mod(unit):
  672. if unit.get("_TS_TEST_DEPENDS_ON_BUILD"):
  673. for_mod_path = unit.get("TS_TEST_FOR_PATH")
  674. unit.ondepends([for_mod_path])