Nenhuma descrição

Api.js 16KB

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