android-install.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env node
  2. module.exports = function (context) {
  3. var path = context.requireCordovaModule('path'),
  4. fs = context.requireCordovaModule('fs'),
  5. shell = context.requireCordovaModule('shelljs'),
  6. projectRoot = context.opts.projectRoot,
  7. plugins = context.opts.plugins || [];
  8. // The plugins array will be empty during platform add
  9. if (plugins.length > 0 && plugins.indexOf('cordova-plugin-wechat') === -1) {
  10. return ;
  11. }
  12. var ConfigParser = null;
  13. try {
  14. ConfigParser = context.requireCordovaModule('cordova-common').ConfigParser;
  15. } catch(e) {
  16. // fallback
  17. ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser');
  18. }
  19. var config = new ConfigParser(path.join(context.opts.projectRoot, "config.xml")),
  20. packageName = config.android_packageName() || config.packageName();
  21. // replace dash (-) with underscore (_)
  22. packageName = packageName.replace(/-/g , "_");
  23. console.info("Running android-install.Hook: " + context.hook + ", Package: " + packageName + ", Path: " + projectRoot + ".");
  24. if (!packageName) {
  25. console.error("Package name could not be found!");
  26. return ;
  27. }
  28. // android platform available?
  29. if (context.opts.cordova.platforms.indexOf("android") === -1) {
  30. console.info("Android platform has not been added.");
  31. return ;
  32. }
  33. var targetDir = path.join(projectRoot, "platforms", "android", "src", packageName.replace(/\./g, path.sep), "wxapi");
  34. targetFiles = ["EntryActivity.java", "WXEntryActivity.java", "WXPayEntryActivity.java"];
  35. if (['after_plugin_add', 'after_plugin_install'].indexOf(context.hook) === -1) {
  36. // remove it?
  37. targetFiles.forEach(function (f) {
  38. try {
  39. fs.unlinkSync(path.join(targetDir, f));
  40. } catch (err) {}
  41. });
  42. } else {
  43. // create directory
  44. shell.mkdir('-p', targetDir);
  45. // sync the content
  46. targetFiles.forEach(function (f) {
  47. fs.readFile(path.join(context.opts.plugin.dir, 'src', 'android', f), {encoding: 'utf-8'}, function (err, data) {
  48. if (err) {
  49. throw err;
  50. }
  51. data = data.replace(/^package __PACKAGE_NAME__;/m, 'package ' + packageName + '.wxapi;');
  52. fs.writeFileSync(path.join(targetDir, f), data);
  53. });
  54. });
  55. }
  56. };