support-kotlin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const fs = require('fs');
  2. const xml2js = require('xml2js');
  3. const PLUGIN_ID = "cordova-plugin-semsx-launcher";
  4. const gradlePath = './platforms/android/app/build.gradle'; // cordova-android@7+ path
  5. let deferral;
  6. function addSupport() {
  7. let defaultArgs = {
  8. kotlin_version: '\text.kotlin_version = "latest.integration"\n\t',
  9. kotlin_android: 'apply plugin: "kotlin-android"',
  10. classpath: ' \t\tclasspath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"'
  11. };
  12. const pluginXML = fs.readFileSync('./plugins/' + PLUGIN_ID + '/plugin.xml').toString();
  13. const gradle = fs.readFileSync(gradlePath).toString();
  14. let text = gradle;
  15. const parser = new xml2js.Parser();
  16. parser.parseString(pluginXML, (error, config) => {
  17. if (error) return;
  18. if (!config.plugin.hasOwnProperty('platform')) return;
  19. for (let x of config.plugin.platform)
  20. if (x['$'].name === 'android') {
  21. if (x['$'].hasOwnProperty('kotlin')) defaultArgs.kotlin_version = `\text.kotlin_version = "${x['$'].kotlin}"\n\t`;
  22. if (x.hasOwnProperty('apply-plugin')) defaultArgs.apply_plugin = x['apply-plugin'];
  23. break;
  24. }
  25. if (!gradle.match(/ext.kotlin_version/g)) append(defaultArgs.kotlin_version, /buildscript(\s*)\{\s*/g);
  26. if (!gradle.match(/kotlin-gradle-plugin/g)) append(defaultArgs.classpath, /classpath\s+(['"])[\w.:]+(['"])/g);
  27. if (!gradle.match(/apply\s+plugin(\s*:\s*)(['"])kotlin-android(['"])/g)) append(defaultArgs.kotlin_android);
  28. if (defaultArgs.apply_plugin)
  29. for (let x of defaultArgs.apply_plugin) {
  30. const reg = new RegExp(`apply\\s+plugin(\\s*:\\s*)(['"])${x}(['"])`, 'g');
  31. if (!gradle.match(reg)) append(`apply plugin: "${x}"`);
  32. }
  33. });
  34. function append(edit, reg) {
  35. if (reg === undefined) reg = /com.android.application['"]/g;
  36. const pos = text.search(reg);
  37. const len = text.match(reg)[0].length;
  38. const header = text.substring(0, pos + len);
  39. const footer = text.substring(pos + len);
  40. text = header + '\n' + edit + footer;
  41. }
  42. fs.writeFileSync(gradlePath, text);
  43. }
  44. module.exports = function (ctx) {
  45. try {
  46. deferral = ctx.requireCordovaModule('q').defer();
  47. addSupport();
  48. deferral.resolve();
  49. } catch (e) {
  50. let msg = e.toString();
  51. console.dir(e);
  52. deferral.reject(msg);
  53. return deferral.promise;
  54. }
  55. };