java.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import _common as common
  2. import ymake
  3. import json
  4. import os
  5. import base64
  6. import six
  7. DELIM = '================================'
  8. CONTRIB_JAVA_PREFIX = 'contrib/java/'
  9. def split_args(s): # TODO quotes, escapes
  10. return list(filter(None, s.split()))
  11. def extract_macro_calls(unit, macro_value_name, macro_calls_delim):
  12. if not unit.get(macro_value_name):
  13. return []
  14. return list(
  15. filter(
  16. None,
  17. map(split_args, unit.get(macro_value_name).replace('$' + macro_value_name, '').split(macro_calls_delim)),
  18. )
  19. )
  20. def extract_macro_calls2(unit, macro_value_name):
  21. if not unit.get(macro_value_name):
  22. return []
  23. calls = []
  24. for call_encoded_args in unit.get(macro_value_name).strip().split():
  25. call_args = json.loads(base64.b64decode(call_encoded_args))
  26. calls.append(call_args)
  27. return calls
  28. def ongenerate_script(unit, *args):
  29. """
  30. heretic@ promised to make tutorial here
  31. Don't forget
  32. Feel free to remind
  33. """
  34. flat, kv = common.sort_by_keywords({'OUT': -1, 'TEMPLATE': -1, 'CUSTOM_PROPERTY': -1}, args)
  35. if len(kv.get('TEMPLATE', [])) > len(kv.get('OUT', [])):
  36. ymake.report_configure_error('To many arguments for TEMPLATE parameter')
  37. prev = unit.get(['GENERATE_SCRIPT_VALUE']) or ''
  38. new_val = (
  39. prev + ' ' + six.ensure_str(base64.b64encode(six.ensure_binary(json.dumps(list(args)), encoding='utf-8')))
  40. ).strip()
  41. unit.set(['GENERATE_SCRIPT_VALUE', new_val])
  42. def onjava_module(unit, *args):
  43. args_delim = unit.get('ARGS_DELIM')
  44. if unit.get('YA_IDE_IDEA') != 'yes':
  45. return
  46. data = {
  47. 'BUNDLE_NAME': unit.name(),
  48. 'PATH': unit.path(),
  49. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  50. 'MODULE_ARGS': unit.get('MODULE_ARGS'),
  51. 'MANAGED_PEERS': '${MANAGED_PEERS}',
  52. 'MANAGED_PEERS_CLOSURE': '${MANAGED_PEERS_CLOSURE}',
  53. 'NON_NAMAGEABLE_PEERS': '${NON_NAMAGEABLE_PEERS}',
  54. 'TEST_CLASSPATH_MANAGED': '${TEST_CLASSPATH_MANAGED}',
  55. 'EXCLUDE': extract_macro_calls(unit, 'EXCLUDE_VALUE', args_delim),
  56. 'JAVA_SRCS': extract_macro_calls(unit, 'JAVA_SRCS_VALUE', args_delim),
  57. 'JAVAC_FLAGS': extract_macro_calls(unit, 'JAVAC_FLAGS_VALUE', args_delim),
  58. 'ANNOTATION_PROCESSOR': extract_macro_calls(unit, 'ANNOTATION_PROCESSOR_VALUE', args_delim),
  59. 'EXTERNAL_JAR': extract_macro_calls(unit, 'EXTERNAL_JAR_VALUE', args_delim),
  60. 'MAVEN_GROUP_ID': extract_macro_calls(unit, 'MAVEN_GROUP_ID_VALUE', args_delim),
  61. 'JAR_INCLUDE_FILTER': extract_macro_calls(unit, 'JAR_INCLUDE_FILTER_VALUE', args_delim),
  62. 'JAR_EXCLUDE_FILTER': extract_macro_calls(unit, 'JAR_EXCLUDE_FILTER_VALUE', args_delim),
  63. # TODO remove when java test dart is in prod
  64. 'UNITTEST_DIR': unit.get('UNITTEST_DIR'),
  65. 'SYSTEM_PROPERTIES': extract_macro_calls(unit, 'SYSTEM_PROPERTIES_VALUE', args_delim),
  66. 'JVM_ARGS': extract_macro_calls(unit, 'JVM_ARGS_VALUE', args_delim),
  67. 'TEST_CWD': extract_macro_calls(unit, 'TEST_CWD_VALUE', args_delim),
  68. 'TEST_FORK_MODE': extract_macro_calls(unit, 'TEST_FORK_MODE', args_delim),
  69. 'SPLIT_FACTOR': extract_macro_calls(unit, 'TEST_SPLIT_FACTOR', args_delim),
  70. 'TIMEOUT': extract_macro_calls(unit, 'TEST_TIMEOUT', args_delim),
  71. 'TAG': extract_macro_calls(unit, 'TEST_TAGS_VALUE', args_delim),
  72. 'SIZE': extract_macro_calls(unit, 'TEST_SIZE_NAME', args_delim),
  73. 'DEPENDS': extract_macro_calls(unit, 'TEST_DEPENDS_VALUE', args_delim),
  74. 'IDEA_EXCLUDE': extract_macro_calls(unit, 'IDEA_EXCLUDE_DIRS_VALUE', args_delim),
  75. 'IDEA_RESOURCE': extract_macro_calls(unit, 'IDEA_RESOURCE_DIRS_VALUE', args_delim),
  76. 'IDEA_MODULE_NAME': extract_macro_calls(unit, 'IDEA_MODULE_NAME_VALUE', args_delim),
  77. 'GENERATE_SCRIPT': extract_macro_calls2(unit, 'GENERATE_SCRIPT_VALUE'),
  78. 'FAKEID': extract_macro_calls(unit, 'FAKEID', args_delim),
  79. 'TEST_DATA': extract_macro_calls(unit, 'TEST_DATA_VALUE', args_delim),
  80. 'JAVA_FORBIDDEN_LIBRARIES': extract_macro_calls(unit, 'JAVA_FORBIDDEN_LIBRARIES_VALUE', args_delim),
  81. 'JDK_RESOURCE': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'),
  82. }
  83. if unit.get('ENABLE_PREVIEW_VALUE') == 'yes' and (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION')) in (
  84. '17',
  85. '20',
  86. '21',
  87. '22',
  88. '23',
  89. ):
  90. data['ENABLE_PREVIEW'] = extract_macro_calls(unit, 'ENABLE_PREVIEW_VALUE', args_delim)
  91. if unit.get('SAVE_JAVAC_GENERATED_SRCS_DIR') and unit.get('SAVE_JAVAC_GENERATED_SRCS_TAR'):
  92. data['SAVE_JAVAC_GENERATED_SRCS_DIR'] = extract_macro_calls(unit, 'SAVE_JAVAC_GENERATED_SRCS_DIR', args_delim)
  93. data['SAVE_JAVAC_GENERATED_SRCS_TAR'] = extract_macro_calls(unit, 'SAVE_JAVAC_GENERATED_SRCS_TAR', args_delim)
  94. if unit.get('JAVA_ADD_DLLS_VALUE') == 'yes':
  95. data['ADD_DLLS_FROM_DEPENDS'] = extract_macro_calls(unit, 'JAVA_ADD_DLLS_VALUE', args_delim)
  96. if unit.get('ERROR_PRONE_VALUE') == 'yes':
  97. data['ERROR_PRONE'] = extract_macro_calls(unit, 'ERROR_PRONE_VALUE', args_delim)
  98. if unit.get('WITH_KOTLIN_VALUE') == 'yes':
  99. data['WITH_KOTLIN'] = extract_macro_calls(unit, 'WITH_KOTLIN_VALUE', args_delim)
  100. if unit.get('KOTLIN_JVM_TARGET'):
  101. data['KOTLIN_JVM_TARGET'] = extract_macro_calls(unit, 'KOTLIN_JVM_TARGET', args_delim)
  102. if unit.get('KOTLINC_FLAGS_VALUE'):
  103. data['KOTLINC_FLAGS'] = extract_macro_calls(unit, 'KOTLINC_FLAGS_VALUE', args_delim)
  104. if unit.get('KOTLINC_OPTS_VALUE'):
  105. data['KOTLINC_OPTS'] = extract_macro_calls(unit, 'KOTLINC_OPTS_VALUE', args_delim)
  106. if unit.get('DIRECT_DEPS_ONLY_VALUE') == 'yes':
  107. data['DIRECT_DEPS_ONLY'] = extract_macro_calls(unit, 'DIRECT_DEPS_ONLY_VALUE', args_delim)
  108. if unit.get('JAVA_EXTERNAL_DEPENDENCIES_VALUE'):
  109. valid = []
  110. for dep in sum(extract_macro_calls(unit, 'JAVA_EXTERNAL_DEPENDENCIES_VALUE', args_delim), []):
  111. if os.path.normpath(dep).startswith('..'):
  112. ymake.report_configure_error(
  113. '{}: {} - relative paths in JAVA_EXTERNAL_DEPENDENCIES is not allowed'.format(unit.path(), dep)
  114. )
  115. elif os.path.isabs(dep):
  116. ymake.report_configure_error(
  117. '{}: {} absolute paths in JAVA_EXTERNAL_DEPENDENCIES is not allowed'.format(unit.path(), dep)
  118. )
  119. else:
  120. valid.append(dep)
  121. if valid:
  122. data['EXTERNAL_DEPENDENCIES'] = [valid]
  123. if unit.get('MAKE_UBERJAR_VALUE') == 'yes':
  124. if unit.get('MODULE_TYPE') != 'JAVA_PROGRAM':
  125. ymake.report_configure_error('{}: UBERJAR supported only for JAVA_PROGRAM module type'.format(unit.path()))
  126. data['UBERJAR'] = extract_macro_calls(unit, 'MAKE_UBERJAR_VALUE', args_delim)
  127. data['UBERJAR_PREFIX'] = extract_macro_calls(unit, 'UBERJAR_PREFIX_VALUE', args_delim)
  128. data['UBERJAR_HIDE_EXCLUDE'] = extract_macro_calls(unit, 'UBERJAR_HIDE_EXCLUDE_VALUE', args_delim)
  129. data['UBERJAR_PATH_EXCLUDE'] = extract_macro_calls(unit, 'UBERJAR_PATH_EXCLUDE_VALUE', args_delim)
  130. data['UBERJAR_MANIFEST_TRANSFORMER_MAIN'] = extract_macro_calls(
  131. unit, 'UBERJAR_MANIFEST_TRANSFORMER_MAIN_VALUE', args_delim
  132. )
  133. data['UBERJAR_MANIFEST_TRANSFORMER_ATTRIBUTE'] = extract_macro_calls(
  134. unit, 'UBERJAR_MANIFEST_TRANSFORMER_ATTRIBUTE_VALUE', args_delim
  135. )
  136. data['UBERJAR_APPENDING_TRANSFORMER'] = extract_macro_calls(
  137. unit, 'UBERJAR_APPENDING_TRANSFORMER_VALUE', args_delim
  138. )
  139. data['UBERJAR_SERVICES_RESOURCE_TRANSFORMER'] = extract_macro_calls(
  140. unit, 'UBERJAR_SERVICES_RESOURCE_TRANSFORMER_VALUE', args_delim
  141. )
  142. if unit.get('WITH_JDK_VALUE') == 'yes':
  143. if unit.get('MODULE_TYPE') != 'JAVA_PROGRAM':
  144. ymake.report_configure_error(
  145. '{}: JDK export supported only for JAVA_PROGRAM module type'.format(unit.path())
  146. )
  147. data['WITH_JDK'] = extract_macro_calls(unit, 'WITH_JDK_VALUE', args_delim)
  148. if not data['EXTERNAL_JAR']:
  149. # IMPORTANT before switching vcs_info.py to python3 the value was always evaluated to $YMAKE_PYTHON but no
  150. # code in java dart parser extracts its value only checks this key for existance.
  151. data['EMBED_VCS'] = [['yes']]
  152. # FORCE_VCS_INFO_UPDATE is responsible for setting special value of VCS_INFO_DISABLE_CACHE__NO_UID__
  153. macro_val = extract_macro_calls(unit, 'FORCE_VCS_INFO_UPDATE', args_delim)
  154. macro_str = macro_val[0][0] if macro_val and macro_val[0] and macro_val[0][0] else ''
  155. if macro_str and macro_str == 'yes':
  156. data['VCS_INFO_DISABLE_CACHE__NO_UID__'] = macro_val
  157. for java_srcs_args in data['JAVA_SRCS']:
  158. external = None
  159. for i in six.moves.range(len(java_srcs_args)):
  160. arg = java_srcs_args[i]
  161. if arg == 'EXTERNAL':
  162. if not i + 1 < len(java_srcs_args):
  163. continue # TODO configure error
  164. ex = java_srcs_args[i + 1]
  165. if ex in ('EXTERNAL', 'SRCDIR', 'PACKAGE_PREFIX', 'EXCLUDE'):
  166. continue # TODO configure error
  167. if external is not None:
  168. continue # TODO configure error
  169. external = ex
  170. if external:
  171. unit.onpeerdir(external)
  172. data = {k: v for k, v in six.iteritems(data) if v}
  173. dart = 'JAVA_DART: ' + six.ensure_str(base64.b64encode(six.ensure_binary(json.dumps(data)))) + '\n' + DELIM + '\n'
  174. unit.set_property(['JAVA_DART_DATA', dart])
  175. def on_add_java_style_checks(unit, *args):
  176. if unit.get('LINT_LEVEL_VALUE') != "none" and common.get_no_lint_value(unit) != 'none':
  177. unit.onadd_check(['JAVA_STYLE', unit.get('LINT_LEVEL_VALUE')] + list(args))
  178. def on_add_kotlin_style_checks(unit, *args):
  179. """
  180. ktlint can be disabled using NO_LINT() and NO_LINT(ktlint)
  181. """
  182. if unit.get('WITH_KOTLIN_VALUE') == 'yes':
  183. if common.get_no_lint_value(unit) == '':
  184. unit.onadd_check(['ktlint'] + list(args))
  185. def on_add_classpath_clash_check(unit, *args):
  186. jdeps_val = (unit.get('CHECK_JAVA_DEPS_VALUE') or '').lower()
  187. if jdeps_val and jdeps_val not in ('yes', 'no', 'strict'):
  188. ymake.report_configure_error('CHECK_JAVA_DEPS: "yes", "no" or "strict" required')
  189. if jdeps_val and jdeps_val != 'no':
  190. unit.onjava_test_deps(jdeps_val)
  191. def on_add_detekt_report_check(unit, *args):
  192. if unit.get('WITH_KOTLIN_VALUE') == 'yes' and unit.get('WITH_KOTLINC_PLUGIN_DETEKT') == 'yes':
  193. unit.onadd_check(['detekt.report'] + list(args))
  194. # Ymake java modules related macroses
  195. def onexternal_jar(unit, *args):
  196. args = list(args)
  197. flat, kv = common.sort_by_keywords({'SOURCES': 1}, args)
  198. if not flat:
  199. ymake.report_configure_error('EXTERNAL_JAR requires exactly one resource URL of compiled jar library')
  200. res = flat[0]
  201. resid = res[4:] if res.startswith('sbr:') else res
  202. unit.set(['JAR_LIB_RESOURCE', resid])
  203. unit.set(['JAR_LIB_RESOURCE_URL', res])
  204. def on_check_java_srcdir(unit, *args):
  205. args = list(args)
  206. if 'SKIP_CHECK_SRCDIR' in args:
  207. return
  208. for arg in args:
  209. if '$' not in arg:
  210. arc_srcdir = os.path.join(unit.get('MODDIR'), arg)
  211. abs_srcdir = unit.resolve(os.path.join("$S/", arc_srcdir))
  212. if not os.path.exists(abs_srcdir) or not os.path.isdir(abs_srcdir):
  213. unit.onsrcdir(os.path.join('${ARCADIA_ROOT}', arc_srcdir))
  214. return
  215. srcdir = common.resolve_common_const(unit.resolve_arc_path(arg))
  216. if srcdir and srcdir.startswith('$S'):
  217. abs_srcdir = unit.resolve(srcdir)
  218. if not os.path.exists(abs_srcdir) or not os.path.isdir(abs_srcdir):
  219. unit.onsrcdir(os.path.join('${ARCADIA_ROOT}', srcdir[3:]))
  220. def on_fill_jar_copy_resources_cmd(unit, *args):
  221. if len(args) == 4:
  222. varname, srcdir, base_classes_dir, reslist = tuple(args)
  223. package = ''
  224. else:
  225. varname, srcdir, base_classes_dir, package, reslist = tuple(args)
  226. dest_dir = os.path.join(base_classes_dir, *package.split('.')) if package else base_classes_dir
  227. var = unit.get(varname)
  228. var += ' && $FS_TOOLS copy_files {} {} {}'.format(
  229. srcdir if srcdir.startswith('"$') else '${CURDIR}/' + srcdir, dest_dir, reslist
  230. )
  231. unit.set([varname, var])
  232. def on_fill_jar_gen_srcs(unit, *args):
  233. varname, jar_type, srcdir, base_classes_dir, java_list, kt_list, groovy_list, res_list = tuple(args[0:8])
  234. resolved_srcdir = unit.resolve_arc_path(srcdir)
  235. if not resolved_srcdir.startswith('$') or resolved_srcdir.startswith('$S'):
  236. return
  237. exclude_pos = args.index('EXCLUDE')
  238. globs = args[7:exclude_pos]
  239. excludes = args[exclude_pos + 1 :]
  240. var = unit.get(varname)
  241. var += ' && ${{cwd:BINDIR}} $YMAKE_PYTHON ${{input:"build/scripts/resolve_java_srcs.py"}} --append -d {} -s {} -k {} -g {} -r {} --include-patterns {}'.format(
  242. srcdir, java_list, kt_list, groovy_list, res_list, ' '.join(globs)
  243. )
  244. if jar_type == 'SRC_JAR':
  245. var += ' --all-resources'
  246. if len(excludes) > 0:
  247. var += ' --exclude-patterns {}'.format(' '.join(excludes))
  248. if unit.get('WITH_KOTLIN_VALUE') == 'yes':
  249. var += ' --resolve-kotlin'
  250. unit.set([varname, var])
  251. def on_check_run_java_prog_classpath(unit, *args):
  252. if len(args) != 1:
  253. ymake.report_configure_error(
  254. 'multiple CLASSPATH elements in RUN_JAVA_PROGRAM invocation no more supported. Use JAVA_RUNTIME_PEERDIR on the JAVA_PROGRAM module instead'
  255. )
  256. def extract_words(words, keys):
  257. kv = {}
  258. k = None
  259. for w in words:
  260. if w in keys:
  261. k = w
  262. else:
  263. if k not in kv:
  264. kv[k] = []
  265. kv[k].append(w)
  266. return kv
  267. def parse_words(words):
  268. kv = extract_words(words, {'OUT', 'TEMPLATE'})
  269. if 'TEMPLATE' not in kv:
  270. kv['TEMPLATE'] = ['template.tmpl']
  271. ws = []
  272. for item in ('OUT', 'TEMPLATE'):
  273. for i, word in list(enumerate(kv[item])):
  274. if word == 'CUSTOM_PROPERTY':
  275. ws += kv[item][i:]
  276. kv[item] = kv[item][:i]
  277. templates = kv['TEMPLATE']
  278. outputs = kv['OUT']
  279. if len(outputs) < len(templates):
  280. ymake.report_configure_error('To many arguments for TEMPLATE parameter')
  281. return
  282. if ws and ws[0] != 'CUSTOM_PROPERTY':
  283. ymake.report_configure_error('''Can't parse {}'''.format(ws))
  284. custom_props = []
  285. for item in ws:
  286. if item == 'CUSTOM_PROPERTY':
  287. custom_props.append([])
  288. else:
  289. custom_props[-1].append(item)
  290. props = []
  291. for p in custom_props:
  292. if not p:
  293. ymake.report_configure_error('Empty CUSTOM_PROPERTY')
  294. continue
  295. props.append('-B')
  296. if len(p) > 1:
  297. props.append(six.ensure_str(base64.b64encode(six.ensure_binary("{}={}".format(p[0], ' '.join(p[1:]))))))
  298. else:
  299. ymake.report_configure_error('CUSTOM_PROPERTY "{}" value is not specified'.format(p[0]))
  300. for i, o in enumerate(outputs):
  301. yield o, templates[min(i, len(templates) - 1)], props
  302. def on_ymake_generate_script(unit, *args):
  303. for out, tmpl, props in parse_words(list(args)):
  304. unit.on_add_gen_java_script([out, tmpl] + list(props))
  305. def on_jdk_version_macro_check(unit, *args):
  306. if len(args) != 1:
  307. unit.message(["error", "Invalid syntax. Single argument required."])
  308. jdk_version = args[0]
  309. available_versions = (
  310. '11',
  311. '17',
  312. '20',
  313. '21',
  314. '22',
  315. '23',
  316. )
  317. if jdk_version not in available_versions:
  318. ymake.report_configure_error(
  319. "Invalid jdk version: {}. {} are available".format(jdk_version, available_versions)
  320. )
  321. if int(jdk_version) >= 19 and unit.get('WITH_JDK_VALUE') != 'yes' and unit.get('MODULE_TAG') == 'JAR_RUNNABLE':
  322. msg = (
  323. "Missing WITH_JDK() macro for JDK version >= 19"
  324. # temporary link with additional explanation
  325. ". For more info see https://clubs.at.yandex-team.ru/arcadia/28543"
  326. )
  327. ymake.report_configure_error(msg)
  328. def _maven_coords_for_project(unit, project_dir):
  329. parts = project_dir.split('/')
  330. g = '.'.join(parts[2:-2])
  331. a = parts[-2]
  332. v = parts[-1]
  333. c = ''
  334. pom_path = unit.resolve(os.path.join('$S', project_dir, 'pom.xml'))
  335. if os.path.exists(pom_path):
  336. import xml.etree.ElementTree as et
  337. with open(pom_path, 'rb') as f:
  338. root = et.fromstring(f.read())
  339. for xpath in ('./{http://maven.apache.org/POM/4.0.0}artifactId', './artifactId'):
  340. artifact = root.find(xpath)
  341. if artifact is not None:
  342. artifact = artifact.text
  343. if a != artifact and a.startswith(artifact):
  344. c = a[len(artifact) :].lstrip('-_')
  345. a = artifact
  346. break
  347. return '{}:{}:{}:{}'.format(g, a, v, c)
  348. def on_setup_maven_export_coords_if_need(unit, *args):
  349. if not unit.enabled('MAVEN_EXPORT'):
  350. return
  351. unit.set(['MAVEN_EXPORT_COORDS_GLOBAL', _maven_coords_for_project(unit, args[0])])
  352. def _get_classpath(unit, dir):
  353. if dir.startswith(CONTRIB_JAVA_PREFIX):
  354. return '\\"{}\\"'.format(_maven_coords_for_project(unit, dir).rstrip(':'))
  355. else:
  356. return 'project(\\":{}\\")'.format(dir.replace('/', ':'))
  357. def on_setup_project_coords_if_needed(unit, *args):
  358. if not unit.enabled('EXPORT_GRADLE'):
  359. return
  360. project_dir = args[0]
  361. if project_dir.startswith(CONTRIB_JAVA_PREFIX):
  362. value = '{}'.format(_get_classpath(unit, project_dir).rstrip(':'))
  363. else:
  364. value = 'project(\\":{}\\")'.format(project_dir.replace('/', ':'))
  365. unit.set(['EXPORT_GRADLE_CLASSPATH', value])