nots.py 34 KB

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