java.py 18 KB

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