Api.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /**
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. var path = require('path');
  18. var Q = require('q');
  19. var AndroidProject = require('./lib/AndroidProject');
  20. var AndroidStudio = require('./lib/AndroidStudio');
  21. var PluginManager = require('cordova-common').PluginManager;
  22. var CordovaLogger = require('cordova-common').CordovaLogger;
  23. var selfEvents = require('cordova-common').events;
  24. var PLATFORM = 'android';
  25. function setupEvents (externalEventEmitter) {
  26. if (externalEventEmitter) {
  27. // This will make the platform internal events visible outside
  28. selfEvents.forwardEventsTo(externalEventEmitter);
  29. return externalEventEmitter;
  30. }
  31. // There is no logger if external emitter is not present,
  32. // so attach a console logger
  33. CordovaLogger.get().subscribe(selfEvents);
  34. return selfEvents;
  35. }
  36. /**
  37. * Class, that acts as abstraction over particular platform. Encapsulates the
  38. * platform's properties and methods.
  39. *
  40. * Platform that implements own PlatformApi instance _should implement all
  41. * prototype methods_ of this class to be fully compatible with cordova-lib.
  42. *
  43. * The PlatformApi instance also should define the following field:
  44. *
  45. * * platform: String that defines a platform name.
  46. */
  47. function Api (platform, platformRootDir, events) {
  48. this.platform = PLATFORM;
  49. this.root = path.resolve(__dirname, '..');
  50. this.builder = 'gradle';
  51. setupEvents(events);
  52. var self = this;
  53. this.locations = {
  54. root: self.root,
  55. www: path.join(self.root, 'assets/www'),
  56. res: path.join(self.root, 'res'),
  57. platformWww: path.join(self.root, 'platform_www'),
  58. configXml: path.join(self.root, 'res/xml/config.xml'),
  59. defaultConfigXml: path.join(self.root, 'cordova/defaults.xml'),
  60. strings: path.join(self.root, 'res/values/strings.xml'),
  61. manifest: path.join(self.root, 'AndroidManifest.xml'),
  62. build: path.join(self.root, 'build'),
  63. javaSrc: path.join(self.root, 'src'),
  64. // NOTE: Due to platformApi spec we need to return relative paths here
  65. cordovaJs: 'bin/templates/project/assets/www/cordova.js',
  66. cordovaJsSrc: 'cordova-js-src'
  67. };
  68. // XXX Override some locations for Android Studio projects
  69. if (AndroidStudio.isAndroidStudioProject(self.root) === true) {
  70. selfEvents.emit('log', 'Android Studio project detected');
  71. this.builder = 'studio';
  72. this.android_studio = true;
  73. this.locations.configXml = path.join(self.root, 'app/src/main/res/xml/config.xml');
  74. this.locations.strings = path.join(self.root, 'app/src/main/res/values/strings.xml');
  75. this.locations.manifest = path.join(self.root, 'app/src/main/AndroidManifest.xml');
  76. // We could have Java Source, we could have other languages
  77. this.locations.javaSrc = path.join(self.root, 'app/src/main/java/');
  78. this.locations.www = path.join(self.root, 'app/src/main/assets/www');
  79. this.locations.res = path.join(self.root, 'app/src/main/res');
  80. }
  81. }
  82. /**
  83. * Installs platform to specified directory and creates a platform project.
  84. *
  85. * @param {String} destination Destination directory, where insatll platform to
  86. * @param {ConfigParser} [config] ConfgiParser instance, used to retrieve
  87. * project creation options, such as package id and project name.
  88. * @param {Object} [options] An options object. The most common options are:
  89. * @param {String} [options.customTemplate] A path to custom template, that
  90. * should override the default one from platform.
  91. * @param {Boolean} [options.link] Flag that indicates that platform's
  92. * sources will be linked to installed platform instead of copying.
  93. * @param {EventEmitter} [events] An EventEmitter instance that will be used for
  94. * logging purposes. If no EventEmitter provided, all events will be logged to
  95. * console
  96. *
  97. * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi
  98. * instance or rejected with CordovaError.
  99. */
  100. Api.createPlatform = function (destination, config, options, events) {
  101. events = setupEvents(events);
  102. var result;
  103. try {
  104. result = require('../../lib/create').create(destination, config, options, events).then(function (destination) {
  105. var PlatformApi = require(path.resolve(destination, 'cordova/Api'));
  106. return new PlatformApi(PLATFORM, destination, events);
  107. });
  108. } catch (e) {
  109. events.emit('error', 'createPlatform is not callable from the android project API.');
  110. throw (e);
  111. }
  112. return result;
  113. };
  114. /**
  115. * Updates already installed platform.
  116. *
  117. * @param {String} destination Destination directory, where platform installed
  118. * @param {Object} [options] An options object. The most common options are:
  119. * @param {String} [options.customTemplate] A path to custom template, that
  120. * should override the default one from platform.
  121. * @param {Boolean} [options.link] Flag that indicates that platform's
  122. * sources will be linked to installed platform instead of copying.
  123. * @param {EventEmitter} [events] An EventEmitter instance that will be used for
  124. * logging purposes. If no EventEmitter provided, all events will be logged to
  125. * console
  126. *
  127. * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi
  128. * instance or rejected with CordovaError.
  129. */
  130. Api.updatePlatform = function (destination, options, events) {
  131. events = setupEvents(events);
  132. var result;
  133. try {
  134. result = require('../../lib/create').update(destination, options, events).then(function (destination) {
  135. var PlatformApi = require(path.resolve(destination, 'cordova/Api'));
  136. return new PlatformApi('android', destination, events);
  137. });
  138. } catch (e) {
  139. events.emit('error', 'updatePlatform is not callable from the android project API, you will need to do this manually.');
  140. throw (e);
  141. }
  142. return result;
  143. };
  144. /**
  145. * Gets a CordovaPlatform object, that represents the platform structure.
  146. *
  147. * @return {CordovaPlatform} A structure that contains the description of
  148. * platform's file structure and other properties of platform.
  149. */
  150. Api.prototype.getPlatformInfo = function () {
  151. var result = {};
  152. result.locations = this.locations;
  153. result.root = this.root;
  154. result.name = this.platform;
  155. result.version = require('./version');
  156. result.projectConfig = this._config;
  157. return result;
  158. };
  159. /**
  160. * Updates installed platform with provided www assets and new app
  161. * configuration. This method is required for CLI workflow and will be called
  162. * each time before build, so the changes, made to app configuration and www
  163. * code, will be applied to platform.
  164. *
  165. * @param {CordovaProject} cordovaProject A CordovaProject instance, that defines a
  166. * project structure and configuration, that should be applied to platform
  167. * (contains project's www location and ConfigParser instance for project's
  168. * config).
  169. *
  170. * @return {Promise} Return a promise either fulfilled, or rejected with
  171. * CordovaError instance.
  172. */
  173. Api.prototype.prepare = function (cordovaProject, prepareOptions) {
  174. return require('./lib/prepare').prepare.call(this, cordovaProject, prepareOptions);
  175. };
  176. /**
  177. * Installs a new plugin into platform. This method only copies non-www files
  178. * (sources, libs, etc.) to platform. It also doesn't resolves the
  179. * dependencies of plugin. Both of handling of www files, such as assets and
  180. * js-files and resolving dependencies are the responsibility of caller.
  181. *
  182. * @param {PluginInfo} plugin A PluginInfo instance that represents plugin
  183. * that will be installed.
  184. * @param {Object} installOptions An options object. Possible options below:
  185. * @param {Boolean} installOptions.link: Flag that specifies that plugin
  186. * sources will be symlinked to app's directory instead of copying (if
  187. * possible).
  188. * @param {Object} installOptions.variables An object that represents
  189. * variables that will be used to install plugin. See more details on plugin
  190. * variables in documentation:
  191. * https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html
  192. *
  193. * @return {Promise} Return a promise either fulfilled, or rejected with
  194. * CordovaError instance.
  195. */
  196. Api.prototype.addPlugin = function (plugin, installOptions) {
  197. var project = AndroidProject.getProjectFile(this.root);
  198. var self = this;
  199. installOptions = installOptions || {};
  200. installOptions.variables = installOptions.variables || {};
  201. // Add PACKAGE_NAME variable into vars
  202. if (!installOptions.variables.PACKAGE_NAME) {
  203. installOptions.variables.PACKAGE_NAME = project.getPackageName();
  204. }
  205. if (this.android_studio === true) {
  206. installOptions.android_studio = true;
  207. }
  208. return Q().then(function () {
  209. // CB-11964: Do a clean when installing the plugin code to get around
  210. // the Gradle bug introduced by the Android Gradle Plugin Version 2.2
  211. // TODO: Delete when the next version of Android Gradle plugin comes out
  212. // Since clean doesn't just clean the build, it also wipes out www, we need
  213. // to pass additional options.
  214. // Do some basic argument parsing
  215. var opts = {};
  216. // Skip cleaning prepared files when not invoking via cordova CLI.
  217. opts.noPrepare = true;
  218. if (!AndroidStudio.isAndroidStudioProject(self.root) && !project.isClean()) {
  219. return self.clean(opts);
  220. }
  221. }).then(function () {
  222. return PluginManager.get(self.platform, self.locations, project).addPlugin(plugin, installOptions);
  223. }).then(function () {
  224. if (plugin.getFrameworks(this.platform).length === 0) return;
  225. selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');
  226. // This should pick the correct builder, not just get gradle
  227. require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();
  228. }.bind(this))
  229. // CB-11022 Return truthy value to prevent running prepare after
  230. .thenResolve(true);
  231. };
  232. /**
  233. * Removes an installed plugin from platform.
  234. *
  235. * Since method accepts PluginInfo instance as input parameter instead of plugin
  236. * id, caller shoud take care of managing/storing PluginInfo instances for
  237. * future uninstalls.
  238. *
  239. * @param {PluginInfo} plugin A PluginInfo instance that represents plugin
  240. * that will be installed.
  241. *
  242. * @return {Promise} Return a promise either fulfilled, or rejected with
  243. * CordovaError instance.
  244. */
  245. Api.prototype.removePlugin = function (plugin, uninstallOptions) {
  246. var project = AndroidProject.getProjectFile(this.root);
  247. if (uninstallOptions && uninstallOptions.usePlatformWww === true && this.android_studio === true) {
  248. uninstallOptions.usePlatformWww = false;
  249. uninstallOptions.android_studio = true;
  250. }
  251. return PluginManager.get(this.platform, this.locations, project)
  252. .removePlugin(plugin, uninstallOptions)
  253. .then(function () {
  254. if (plugin.getFrameworks(this.platform).length === 0) return;
  255. selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');
  256. require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();
  257. }.bind(this))
  258. // CB-11022 Return truthy value to prevent running prepare after
  259. .thenResolve(true);
  260. };
  261. /**
  262. * Builds an application package for current platform.
  263. *
  264. * @param {Object} buildOptions A build options. This object's structure is
  265. * highly depends on platform's specific. The most common options are:
  266. * @param {Boolean} buildOptions.debug Indicates that packages should be
  267. * built with debug configuration. This is set to true by default unless the
  268. * 'release' option is not specified.
  269. * @param {Boolean} buildOptions.release Indicates that packages should be
  270. * built with release configuration. If not set to true, debug configuration
  271. * will be used.
  272. * @param {Boolean} buildOptions.device Specifies that built app is intended
  273. * to run on device
  274. * @param {Boolean} buildOptions.emulator: Specifies that built app is
  275. * intended to run on emulator
  276. * @param {String} buildOptions.target Specifies the device id that will be
  277. * used to run built application.
  278. * @param {Boolean} buildOptions.nobuild Indicates that this should be a
  279. * dry-run call, so no build artifacts will be produced.
  280. * @param {String[]} buildOptions.archs Specifies chip architectures which
  281. * app packages should be built for. List of valid architectures is depends on
  282. * platform.
  283. * @param {String} buildOptions.buildConfig The path to build configuration
  284. * file. The format of this file is depends on platform.
  285. * @param {String[]} buildOptions.argv Raw array of command-line arguments,
  286. * passed to `build` command. The purpose of this property is to pass a
  287. * platform-specific arguments, and eventually let platform define own
  288. * arguments processing logic.
  289. *
  290. * @return {Promise<Object[]>} A promise either fulfilled with an array of build
  291. * artifacts (application packages) if package was built successfully,
  292. * or rejected with CordovaError. The resultant build artifact objects is not
  293. * strictly typed and may conatin arbitrary set of fields as in sample below.
  294. *
  295. * {
  296. * architecture: 'x86',
  297. * buildType: 'debug',
  298. * path: '/path/to/build',
  299. * type: 'app'
  300. * }
  301. *
  302. * The return value in most cases will contain only one item but in some cases
  303. * there could be multiple items in output array, e.g. when multiple
  304. * arhcitectures is specified.
  305. */
  306. Api.prototype.build = function (buildOptions) {
  307. var self = this;
  308. if (this.android_studio) {
  309. buildOptions.studio = true;
  310. }
  311. return require('./lib/check_reqs').run().then(function () {
  312. return require('./lib/build').run.call(self, buildOptions);
  313. }).then(function (buildResults) {
  314. // Cast build result to array of build artifacts
  315. return buildResults.apkPaths.map(function (apkPath) {
  316. return {
  317. buildType: buildResults.buildType,
  318. buildMethod: buildResults.buildMethod,
  319. path: apkPath,
  320. type: 'apk'
  321. };
  322. });
  323. });
  324. };
  325. /**
  326. * Builds an application package for current platform and runs it on
  327. * specified/default device. If no 'device'/'emulator'/'target' options are
  328. * specified, then tries to run app on default device if connected, otherwise
  329. * runs the app on emulator.
  330. *
  331. * @param {Object} runOptions An options object. The structure is the same
  332. * as for build options.
  333. *
  334. * @return {Promise} A promise either fulfilled if package was built and ran
  335. * successfully, or rejected with CordovaError.
  336. */
  337. Api.prototype.run = function (runOptions) {
  338. var self = this;
  339. return require('./lib/check_reqs').run().then(function () {
  340. return require('./lib/run').run.call(self, runOptions);
  341. });
  342. };
  343. /**
  344. * Cleans out the build artifacts from platform's directory, and also
  345. * cleans out the platform www directory if called without options specified.
  346. *
  347. * @return {Promise} Return a promise either fulfilled, or rejected with
  348. * CordovaError.
  349. */
  350. Api.prototype.clean = function (cleanOptions) {
  351. var self = this;
  352. if (this.android_studio) {
  353. // This will lint, checking for null won't
  354. if (typeof cleanOptions === 'undefined') {
  355. cleanOptions = {};
  356. }
  357. cleanOptions.studio = true;
  358. }
  359. return require('./lib/check_reqs').run().then(function () {
  360. return require('./lib/build').runClean.call(self, cleanOptions);
  361. }).then(function () {
  362. return require('./lib/prepare').clean.call(self, cleanOptions);
  363. });
  364. };
  365. /**
  366. * Performs a requirements check for current platform. Each platform defines its
  367. * own set of requirements, which should be resolved before platform can be
  368. * built successfully.
  369. *
  370. * @return {Promise<Requirement[]>} Promise, resolved with set of Requirement
  371. * objects for current platform.
  372. */
  373. Api.prototype.requirements = function () {
  374. return require('./lib/check_reqs').check_all();
  375. };
  376. module.exports = Api;