Api.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. /* jslint node: true */
  18. var fs = require('fs');
  19. var path = require('path');
  20. var unorm = require('unorm');
  21. var projectFile = require('./lib/projectFile');
  22. var check_reqs = require('./lib/check_reqs');
  23. var CordovaError = require('cordova-common').CordovaError;
  24. var CordovaLogger = require('cordova-common').CordovaLogger;
  25. var events = require('cordova-common').events;
  26. var PluginManager = require('cordova-common').PluginManager;
  27. var Q = require('q');
  28. var util = require('util');
  29. function setupEvents (externalEventEmitter) {
  30. if (externalEventEmitter) {
  31. // This will make the platform internal events visible outside
  32. events.forwardEventsTo(externalEventEmitter);
  33. } else {
  34. // There is no logger if external emitter is not present,
  35. // so attach a console logger
  36. CordovaLogger.get().subscribe(events);
  37. }
  38. }
  39. /**
  40. * Creates a new PlatformApi instance.
  41. *
  42. * @param {String} [platform] Platform name, used for backward compatibility
  43. * w/ PlatformPoly (CordovaLib).
  44. * @param {String} [platformRootDir] Platform root location, used for backward
  45. * compatibility w/ PlatformPoly (CordovaLib).
  46. * @param {EventEmitter} [events] An EventEmitter instance that will be used for
  47. * logging purposes. If no EventEmitter provided, all events will be logged to
  48. * console
  49. */
  50. function Api (platform, platformRootDir, events) {
  51. // 'platform' property is required as per PlatformApi spec
  52. this.platform = platform || 'ios';
  53. this.root = platformRootDir || path.resolve(__dirname, '..');
  54. setupEvents(events);
  55. var xcodeProjDir;
  56. var xcodeCordovaProj;
  57. try {
  58. xcodeProjDir = fs.readdirSync(this.root).filter(function (e) { return e.match(/\.xcodeproj$/i); })[0];
  59. if (!xcodeProjDir) {
  60. throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');
  61. }
  62. var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep) + 1, xcodeProjDir.indexOf('.xcodeproj'));
  63. xcodeCordovaProj = path.join(this.root, cordovaProjName);
  64. } catch (e) {
  65. throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');
  66. }
  67. this.locations = {
  68. root: this.root,
  69. www: path.join(this.root, 'www'),
  70. platformWww: path.join(this.root, 'platform_www'),
  71. configXml: path.join(xcodeCordovaProj, 'config.xml'),
  72. defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),
  73. pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'),
  74. xcodeProjDir: path.join(this.root, xcodeProjDir),
  75. xcodeCordovaProj: xcodeCordovaProj,
  76. // NOTE: this is required by browserify logic.
  77. // As per platformApi spec we return relative to template root paths here
  78. cordovaJs: 'bin/CordovaLib/cordova.js',
  79. cordovaJsSrc: 'bin/cordova-js-src'
  80. };
  81. }
  82. /**
  83. * Creates platform in a specified directory.
  84. *
  85. * @param {String} destination Destination directory, where install 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. setupEvents(events);
  102. // CB-6992 it is necessary to normalize characters
  103. // because node and shell scripts handles unicode symbols differently
  104. // We need to normalize the name to NFD form since iOS uses NFD unicode form
  105. var name = unorm.nfd(config.name());
  106. var result;
  107. try {
  108. result = require('../../../lib/create')
  109. .createProject(destination, config.packageName(), name, options)
  110. .then(function () {
  111. // after platform is created we return Api instance based on new Api.js location
  112. // This is required to correctly resolve paths in the future api calls
  113. var PlatformApi = require(path.resolve(destination, 'cordova/Api'));
  114. return new PlatformApi('ios', destination, events);
  115. });
  116. } catch (e) {
  117. events.emit('error', 'createPlatform is not callable from the iOS project API.');
  118. throw (e);
  119. }
  120. return result;
  121. };
  122. /**
  123. * Updates already installed platform.
  124. *
  125. * @param {String} destination Destination directory, where platform installed
  126. * @param {Object} [options] An options object. The most common options are:
  127. * @param {String} [options.customTemplate] A path to custom template, that
  128. * should override the default one from platform.
  129. * @param {Boolean} [options.link] Flag that indicates that platform's
  130. * sources will be linked to installed platform instead of copying.
  131. * @param {EventEmitter} [events] An EventEmitter instance that will be used for
  132. * logging purposes. If no EventEmitter provided, all events will be logged to
  133. * console
  134. *
  135. * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi
  136. * instance or rejected with CordovaError.
  137. */
  138. Api.updatePlatform = function (destination, options, events) {
  139. setupEvents(events);
  140. var result;
  141. try {
  142. result = require('../../../lib/create')
  143. .updateProject(destination, options)
  144. .then(function () {
  145. var PlatformApi = require(path.resolve(destination, 'cordova/Api'));
  146. return new PlatformApi('ios', destination, events);
  147. });
  148. } catch (e) {
  149. events.emit('error', 'updatePlatform is not callable from the iOS project API, you will need to do this manually.');
  150. throw (e);
  151. }
  152. return result;
  153. };
  154. /**
  155. * Gets a CordovaPlatform object, that represents the platform structure.
  156. *
  157. * @return {CordovaPlatform} A structure that contains the description of
  158. * platform's file structure and other properties of platform.
  159. */
  160. Api.prototype.getPlatformInfo = function () {
  161. var result = {};
  162. result.locations = this.locations;
  163. result.root = this.root;
  164. result.name = this.platform;
  165. result.version = require('./version');
  166. result.projectConfig = this._config;
  167. return result;
  168. };
  169. /**
  170. * Updates installed platform with provided www assets and new app
  171. * configuration. This method is required for CLI workflow and will be called
  172. * each time before build, so the changes, made to app configuration and www
  173. * code, will be applied to platform.
  174. *
  175. * @param {CordovaProject} cordovaProject A CordovaProject instance, that defines a
  176. * project structure and configuration, that should be applied to platform
  177. * (contains project's www location and ConfigParser instance for project's
  178. * config).
  179. *
  180. * @return {Promise} Return a promise either fulfilled, or rejected with
  181. * CordovaError instance.
  182. */
  183. Api.prototype.prepare = function (cordovaProject) {
  184. return require('./lib/prepare').prepare.call(this, cordovaProject);
  185. };
  186. /**
  187. * Installs a new plugin into platform. It doesn't resolves plugin dependencies.
  188. *
  189. * @param {PluginInfo} plugin A PluginInfo instance that represents plugin
  190. * that will be installed.
  191. * @param {Object} installOptions An options object. Possible options below:
  192. * @param {Boolean} installOptions.link: Flag that specifies that plugin
  193. * sources will be symlinked to app's directory instead of copying (if
  194. * possible).
  195. * @param {Object} installOptions.variables An object that represents
  196. * variables that will be used to install plugin. See more details on plugin
  197. * variables in documentation:
  198. * https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html
  199. *
  200. * @return {Promise} Return a promise either fulfilled, or rejected with
  201. * CordovaError instance.
  202. */
  203. Api.prototype.addPlugin = function (plugin, installOptions) {
  204. var xcodeproj = projectFile.parse(this.locations);
  205. var self = this;
  206. installOptions = installOptions || {};
  207. installOptions.variables = installOptions.variables || {};
  208. // Add PACKAGE_NAME variable into vars
  209. if (!installOptions.variables.PACKAGE_NAME) {
  210. installOptions.variables.PACKAGE_NAME = xcodeproj.getPackageName();
  211. }
  212. return PluginManager.get(self.platform, self.locations, xcodeproj)
  213. .addPlugin(plugin, installOptions)
  214. .then(function () {
  215. var frameworkTags = plugin.getFrameworks(self.platform);
  216. var frameworkPods = frameworkTags.filter(function (obj) {
  217. return (obj.type === 'podspec');
  218. });
  219. return Q.resolve(frameworkPods);
  220. })
  221. .then(function (frameworkPods) {
  222. if (!(frameworkPods.length)) {
  223. return Q.resolve();
  224. }
  225. var project_dir = self.locations.root;
  226. var project_name = self.locations.xcodeCordovaProj.split('/').pop();
  227. var Podfile = require('./lib/Podfile').Podfile;
  228. var PodsJson = require('./lib/PodsJson').PodsJson;
  229. events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type="podspec"');
  230. var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));
  231. var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name);
  232. frameworkPods.forEach(function (obj) {
  233. var podJson = {
  234. name: obj.src,
  235. type: obj.type,
  236. spec: obj.spec
  237. };
  238. var val = podsjsonFile.get(podJson.name);
  239. if (val) { // found
  240. if (podJson.spec !== val.spec) { // exists, different spec, print warning
  241. events.emit('warn', plugin.id + ' depends on ' + podJson.name + '@' + podJson.spec + ', which conflicts with another plugin. ' + podJson.name + '@' + val.spec + ' is already installed and was not overwritten.');
  242. }
  243. // increment count, but don't add in Podfile because it already exists
  244. podsjsonFile.increment(podJson.name);
  245. } else { // not found, write new
  246. podJson.count = 1;
  247. podsjsonFile.setJson(podJson.name, podJson);
  248. // add to Podfile
  249. podfileFile.addSpec(podJson.name, podJson.spec);
  250. }
  251. });
  252. // now that all the pods have been processed, write to pods.json
  253. podsjsonFile.write();
  254. // only write and pod install if the Podfile changed
  255. if (podfileFile.isDirty()) {
  256. podfileFile.write();
  257. events.emit('verbose', 'Running `pod install` (to install plugins)');
  258. return podfileFile.install(check_reqs.check_cocoapods);
  259. } else {
  260. events.emit('verbose', 'Podfile unchanged, skipping `pod install`');
  261. }
  262. })
  263. // CB-11022 return non-falsy value to indicate
  264. // that there is no need to run prepare after
  265. .thenResolve(true);
  266. };
  267. /**
  268. * Removes an installed plugin from platform.
  269. *
  270. * Since method accepts PluginInfo instance as input parameter instead of plugin
  271. * id, caller shoud take care of managing/storing PluginInfo instances for
  272. * future uninstalls.
  273. *
  274. * @param {PluginInfo} plugin A PluginInfo instance that represents plugin
  275. * that will be installed.
  276. *
  277. * @return {Promise} Return a promise either fulfilled, or rejected with
  278. * CordovaError instance.
  279. */
  280. Api.prototype.removePlugin = function (plugin, uninstallOptions) {
  281. var xcodeproj = projectFile.parse(this.locations);
  282. var self = this;
  283. return PluginManager.get(self.platform, self.locations, xcodeproj)
  284. .removePlugin(plugin, uninstallOptions)
  285. .then(function () {
  286. var frameworkTags = plugin.getFrameworks(self.platform);
  287. var frameworkPods = frameworkTags.filter(function (obj) {
  288. return (obj.type === 'podspec');
  289. });
  290. return Q.resolve(frameworkPods);
  291. })
  292. .then(function (frameworkPods) {
  293. if (!(frameworkPods.length)) {
  294. return Q.resolve();
  295. }
  296. var project_dir = self.locations.root;
  297. var project_name = self.locations.xcodeCordovaProj.split('/').pop();
  298. var Podfile = require('./lib/Podfile').Podfile;
  299. var PodsJson = require('./lib/PodsJson').PodsJson;
  300. events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type=\"podspec\"'); /* eslint no-useless-escape : 0 */
  301. var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));
  302. var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name);
  303. frameworkPods.forEach(function (obj) {
  304. var podJson = {
  305. name: obj.src,
  306. type: obj.type,
  307. spec: obj.spec
  308. };
  309. var val = podsjsonFile.get(podJson.name);
  310. if (val) { // found, decrement count
  311. podsjsonFile.decrement(podJson.name);
  312. } else { // not found (perhaps a sync error)
  313. var message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */
  314. events.emit('verbose', message);
  315. }
  316. // always remove from the Podfile
  317. podfileFile.removeSpec(podJson.name);
  318. });
  319. // now that all the pods have been processed, write to pods.json
  320. podsjsonFile.write();
  321. if (podfileFile.isDirty()) {
  322. podfileFile.write();
  323. events.emit('verbose', 'Running `pod install` (to uninstall pods)');
  324. return podfileFile.install(check_reqs.check_cocoapods);
  325. } else {
  326. events.emit('verbose', 'Podfile unchanged, skipping `pod install`');
  327. }
  328. })
  329. // CB-11022 return non-falsy value to indicate
  330. // that there is no need to run prepare after
  331. .thenResolve(true);
  332. };
  333. /**
  334. * Builds an application package for current platform.
  335. *
  336. * @param {Object} buildOptions A build options. This object's structure is
  337. * highly depends on platform's specific. The most common options are:
  338. * @param {Boolean} buildOptions.debug Indicates that packages should be
  339. * built with debug configuration. This is set to true by default unless the
  340. * 'release' option is not specified.
  341. * @param {Boolean} buildOptions.release Indicates that packages should be
  342. * built with release configuration. If not set to true, debug configuration
  343. * will be used.
  344. * @param {Boolean} buildOptions.device Specifies that built app is intended
  345. * to run on device
  346. * @param {Boolean} buildOptions.emulator: Specifies that built app is
  347. * intended to run on emulator
  348. * @param {String} buildOptions.target Specifies the device id that will be
  349. * used to run built application.
  350. * @param {Boolean} buildOptions.nobuild Indicates that this should be a
  351. * dry-run call, so no build artifacts will be produced.
  352. * @param {String[]} buildOptions.archs Specifies chip architectures which
  353. * app packages should be built for. List of valid architectures is depends on
  354. * platform.
  355. * @param {String} buildOptions.buildConfig The path to build configuration
  356. * file. The format of this file is depends on platform.
  357. * @param {String[]} buildOptions.argv Raw array of command-line arguments,
  358. * passed to `build` command. The purpose of this property is to pass a
  359. * platform-specific arguments, and eventually let platform define own
  360. * arguments processing logic.
  361. *
  362. * @return {Promise} Return a promise either fulfilled, or rejected with
  363. * CordovaError instance.
  364. */
  365. Api.prototype.build = function (buildOptions) {
  366. var self = this;
  367. return check_reqs.run()
  368. .then(function () {
  369. return require('./lib/build').run.call(self, buildOptions);
  370. });
  371. };
  372. /**
  373. * Builds an application package for current platform and runs it on
  374. * specified/default device. If no 'device'/'emulator'/'target' options are
  375. * specified, then tries to run app on default device if connected, otherwise
  376. * runs the app on emulator.
  377. *
  378. * @param {Object} runOptions An options object. The structure is the same
  379. * as for build options.
  380. *
  381. * @return {Promise} A promise either fulfilled if package was built and ran
  382. * successfully, or rejected with CordovaError.
  383. */
  384. Api.prototype.run = function (runOptions) {
  385. var self = this;
  386. return check_reqs.run()
  387. .then(function () {
  388. return require('./lib/run').run.call(self, runOptions);
  389. });
  390. };
  391. /**
  392. * Cleans out the build artifacts from platform's directory.
  393. *
  394. * @return {Promise} Return a promise either fulfilled, or rejected with
  395. * CordovaError.
  396. */
  397. Api.prototype.clean = function (cleanOptions) {
  398. var self = this;
  399. return check_reqs.run()
  400. .then(function () {
  401. return require('./lib/clean').run.call(self, cleanOptions);
  402. })
  403. .then(function () {
  404. return require('./lib/prepare').clean.call(self, cleanOptions);
  405. });
  406. };
  407. /**
  408. * Performs a requirements check for current platform. Each platform defines its
  409. * own set of requirements, which should be resolved before platform can be
  410. * built successfully.
  411. *
  412. * @return {Promise<Requirement[]>} Promise, resolved with set of Requirement
  413. * objects for current platform.
  414. */
  415. Api.prototype.requirements = function () {
  416. return check_reqs.check_all();
  417. };
  418. module.exports = Api;