1const { withProjectBuildGradle } = require('@expo/config-plugins');
2const kotlinClassPath = 'org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion';
3
4const withKotlinGradle = (config, version) => {
5  return withProjectBuildGradle(config, config => {
6    if (config.modResults.language === 'groovy') {
7      config.modResults.contents = setKotlinVersion(config.modResults.contents, version);
8      config.modResults.contents = setKotlinClassPath(config.modResults.contents);
9    } else {
10      throw new Error('Cannot setup kotlin because the build.gradle is not groovy');
11    }
12    return config;
13  });
14};
15
16function setKotlinVersion(buildGradle, version) {
17  const pattern = /kotlinVersion\s?=\s?(["'])(?:(?=(\\?))\2.)*?\1/g;
18  const replacement = `kotlinVersion = "${version}"`;
19  if (buildGradle.match(pattern)) {
20    // Select kotlinVersion = '***' and replace the contents between the quotes.
21    return buildGradle.replace(pattern, replacement);
22  }
23  return buildGradle.replace(
24    /ext\s?{/,
25    `ext {
26        ${replacement}`
27  );
28}
29
30function setKotlinClassPath(buildGradle) {
31  if (buildGradle.includes(kotlinClassPath)) {
32    return buildGradle;
33  }
34
35  return buildGradle.replace(
36    /dependencies\s?{/,
37    `dependencies {
38        classpath "${kotlinClassPath}"`
39  );
40}
41
42const withUnimodulesTestCore = (config) => {
43    return withKotlinGradle(config, '1.3.50');
44}
45
46module.exports = withUnimodulesTestCore;