java.py 15 KB

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