Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

build.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #!/usr/bin/env node
  2. /*
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing,
  12. software distributed under the License is distributed on an
  13. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. KIND, either express or implied. See the License for the
  15. specific language governing permissions and limitations
  16. under the License.
  17. */
  18. var Q = require('q');
  19. var path = require('path');
  20. var fs = require('fs');
  21. var nopt = require('nopt');
  22. var Adb = require('./Adb');
  23. var builders = require('./builders/builders');
  24. var events = require('cordova-common').events;
  25. var spawn = require('cordova-common').superspawn.spawn;
  26. var CordovaError = require('cordova-common').CordovaError;
  27. var PackageType = require('./PackageType');
  28. module.exports.parseBuildOptions = parseOpts;
  29. function parseOpts (options, resolvedTarget, projectRoot) {
  30. options = options || {};
  31. options.argv = nopt({
  32. prepenv: Boolean,
  33. versionCode: String,
  34. minSdkVersion: String,
  35. maxSdkVersion: String,
  36. targetSdkVersion: String,
  37. gradleArg: [String, Array],
  38. keystore: path,
  39. alias: String,
  40. storePassword: String,
  41. password: String,
  42. keystoreType: String,
  43. packageType: String
  44. }, {}, options.argv, 0);
  45. // Android Studio Build method is the default
  46. var ret = {
  47. buildType: options.release ? 'release' : 'debug',
  48. prepEnv: options.argv.prepenv,
  49. arch: resolvedTarget && resolvedTarget.arch,
  50. extraArgs: []
  51. };
  52. if (options.argv.versionCode) { ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode); }
  53. if (options.argv.minSdkVersion) { ret.extraArgs.push('-PcdvMinSdkVersion=' + options.argv.minSdkVersion); }
  54. if (options.argv.maxSdkVersion) { ret.extraArgs.push('-PcdvMaxSdkVersion=' + options.argv.maxSdkVersion); }
  55. if (options.argv.targetSdkVersion) { ret.extraArgs.push('-PcdvTargetSdkVersion=' + options.argv.targetSdkVersion); }
  56. if (options.argv.gradleArg) {
  57. ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg);
  58. }
  59. var packageArgs = {};
  60. if (options.argv.keystore) { packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore)); }
  61. ['alias', 'storePassword', 'password', 'keystoreType', 'packageType'].forEach(function (flagName) {
  62. if (options.argv[flagName]) { packageArgs[flagName] = options.argv[flagName]; }
  63. });
  64. var buildConfig = options.buildConfig;
  65. // If some values are not specified as command line arguments - use build config to supplement them.
  66. // Command line arguments have precedence over build config.
  67. if (buildConfig) {
  68. if (!fs.existsSync(buildConfig)) {
  69. throw new Error('Specified build config file does not exist: ' + buildConfig);
  70. }
  71. events.emit('log', 'Reading build config file: ' + path.resolve(buildConfig));
  72. var buildjson = fs.readFileSync(buildConfig, 'utf8');
  73. var config = JSON.parse(buildjson.replace(/^\ufeff/, '')); // Remove BOM
  74. if (config.android && config.android[ret.buildType]) {
  75. var androidInfo = config.android[ret.buildType];
  76. if (androidInfo.keystore && !packageArgs.keystore) {
  77. if (androidInfo.keystore.substr(0, 1) === '~') {
  78. androidInfo.keystore = process.env.HOME + androidInfo.keystore.substr(1);
  79. }
  80. packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore);
  81. events.emit('log', 'Reading the keystore from: ' + packageArgs.keystore);
  82. }
  83. ['alias', 'storePassword', 'password', 'keystoreType', 'packageType'].forEach(function (key) {
  84. packageArgs[key] = packageArgs[key] || androidInfo[key];
  85. });
  86. }
  87. }
  88. if (packageArgs.keystore && packageArgs.alias) {
  89. ret.packageInfo = new PackageInfo(packageArgs.keystore, packageArgs.alias, packageArgs.storePassword,
  90. packageArgs.password, packageArgs.keystoreType);
  91. }
  92. if (!ret.packageInfo) {
  93. // The following loop is to decide whether to print a warning about generating a signed archive
  94. // We only want to produce a warning if they are using a config property that is related to signing, but
  95. // missing the required properties for signing. We don't want to produce a warning if they are simply
  96. // using a build property that isn't related to signing, such as --packageType
  97. let shouldWarn = false;
  98. const signingKeys = ['keystore', 'alias', 'storePassword', 'password', 'keystoreType'];
  99. for (let key in packageArgs) {
  100. if (!shouldWarn && signingKeys.indexOf(key) > -1) {
  101. // If we enter this condition, we have a key used for signing a build,
  102. // but we are missing some required signing properties
  103. shouldWarn = true;
  104. }
  105. }
  106. if (shouldWarn) {
  107. events.emit('warn', '\'keystore\' and \'alias\' need to be specified to generate a signed archive.');
  108. }
  109. }
  110. if (packageArgs.packageType) {
  111. const VALID_PACKAGE_TYPES = [PackageType.APK, PackageType.BUNDLE];
  112. if (VALID_PACKAGE_TYPES.indexOf(packageArgs.packageType) === -1) {
  113. events.emit('warn', '"' + packageArgs.packageType + '" is an invalid packageType. Valid values are: ' + VALID_PACKAGE_TYPES.join(', ') + '\nDefaulting packageType to ' + PackageType.APK);
  114. ret.packageType = PackageType.APK;
  115. } else {
  116. ret.packageType = packageArgs.packageType;
  117. }
  118. } else {
  119. ret.packageType = PackageType.APK;
  120. }
  121. return ret;
  122. }
  123. /*
  124. * Builds the project with the specifed options
  125. * Returns a promise.
  126. */
  127. module.exports.runClean = function (options) {
  128. var opts = parseOpts(options, null, this.root);
  129. var builder = builders.getBuilder();
  130. return builder.prepEnv(opts).then(function () {
  131. return builder.clean(opts);
  132. });
  133. };
  134. /**
  135. * Builds the project with the specifed options.
  136. *
  137. * @param {BuildOptions} options A set of options. See PlatformApi.build
  138. * method documentation for reference.
  139. * @param {Object} optResolvedTarget A deployment target. Used to pass
  140. * target architecture from upstream 'run' call. TODO: remove this option in
  141. * favor of setting buildOptions.archs field.
  142. *
  143. * @return {Promise<Object>} Promise, resolved with built packages
  144. * information.
  145. */
  146. module.exports.run = function (options, optResolvedTarget) {
  147. var opts = parseOpts(options, optResolvedTarget, this.root);
  148. var builder = builders.getBuilder();
  149. return builder.prepEnv(opts).then(function () {
  150. if (opts.prepEnv) {
  151. events.emit('verbose', 'Build file successfully prepared.');
  152. return;
  153. }
  154. return builder.build(opts).then(function () {
  155. var paths;
  156. if (opts.packageType === PackageType.BUNDLE) {
  157. paths = builder.findOutputBundles(opts.buildType);
  158. events.emit('log', 'Built the following bundle(s): \n\t' + paths.join('\n\t'));
  159. } else {
  160. paths = builder.findOutputApks(opts.buildType, opts.arch);
  161. events.emit('log', 'Built the following apk(s): \n\t' + paths.join('\n\t'));
  162. }
  163. return {
  164. paths: paths,
  165. buildType: opts.buildType
  166. };
  167. });
  168. });
  169. };
  170. /*
  171. * Detects the architecture of a device/emulator
  172. * Returns "arm" or "x86".
  173. */
  174. module.exports.detectArchitecture = function (target) {
  175. function helper () {
  176. return Adb.shell(target, 'cat /proc/cpuinfo').then(function (output) {
  177. return /intel/i.exec(output) ? 'x86' : 'arm';
  178. });
  179. }
  180. // It sometimes happens (at least on OS X), that this command will hang forever.
  181. // To fix it, either unplug & replug device, or restart adb server.
  182. return helper().timeout(1000, new CordovaError('Device communication timed out. Try unplugging & replugging the device.')).then(null, function (err) {
  183. if (/timed out/.exec('' + err)) {
  184. // adb kill-server doesn't seem to do the trick.
  185. // Could probably find a x-platform version of killall, but I'm not actually
  186. // sure that this scenario even happens on non-OSX machines.
  187. events.emit('verbose', 'adb timed out while detecting device/emulator architecture. Killing adb and trying again.');
  188. return spawn('killall', ['adb']).then(function () {
  189. return helper().then(null, function () {
  190. // The double kill is sadly often necessary, at least on mac.
  191. events.emit('warn', 'adb timed out a second time while detecting device/emulator architecture. Killing adb and trying again.');
  192. return spawn('killall', ['adb']).then(function () {
  193. return helper().then(null, function () {
  194. return Q.reject(new CordovaError('adb timed out a third time while detecting device/emulator architecture. Try unplugging & replugging the device.'));
  195. });
  196. });
  197. });
  198. }, function () {
  199. // For non-killall OS's.
  200. return Q.reject(err);
  201. });
  202. }
  203. throw err;
  204. });
  205. };
  206. module.exports.findBestApkForArchitecture = function (buildResults, arch) {
  207. var paths = buildResults.apkPaths.filter(function (p) {
  208. var apkName = path.basename(p);
  209. if (buildResults.buildType === 'debug') {
  210. return /-debug/.exec(apkName);
  211. }
  212. return !/-debug/.exec(apkName);
  213. });
  214. var archPattern = new RegExp('-' + arch);
  215. var hasArchPattern = /-x86|-arm/;
  216. for (var i = 0; i < paths.length; ++i) {
  217. var apkName = path.basename(paths[i]);
  218. if (hasArchPattern.exec(apkName)) {
  219. if (archPattern.exec(apkName)) {
  220. return paths[i];
  221. }
  222. } else {
  223. return paths[i];
  224. }
  225. }
  226. throw new Error('Could not find apk architecture: ' + arch + ' build-type: ' + buildResults.buildType);
  227. };
  228. function PackageInfo (keystore, alias, storePassword, password, keystoreType) {
  229. this.keystore = {
  230. 'name': 'key.store',
  231. 'value': keystore
  232. };
  233. this.alias = {
  234. 'name': 'key.alias',
  235. 'value': alias
  236. };
  237. if (storePassword) {
  238. this.storePassword = {
  239. 'name': 'key.store.password',
  240. 'value': storePassword
  241. };
  242. }
  243. if (password) {
  244. this.password = {
  245. 'name': 'key.alias.password',
  246. 'value': password
  247. };
  248. }
  249. if (keystoreType) {
  250. this.keystoreType = {
  251. 'name': 'key.store.type',
  252. 'value': keystoreType
  253. };
  254. }
  255. }
  256. PackageInfo.prototype = {
  257. toProperties: function () {
  258. var self = this;
  259. var result = '';
  260. Object.keys(self).forEach(function (key) {
  261. result += self[key].name;
  262. result += '=';
  263. result += self[key].value.replace(/\\/g, '\\\\');
  264. result += '\n';
  265. });
  266. return result;
  267. }
  268. };
  269. module.exports.help = function () {
  270. console.log('Usage: ' + path.relative(process.cwd(), path.join('../build')) + ' [flags] [Signed APK flags]');
  271. console.log('Flags:');
  272. console.log(' \'--debug\': will build project in debug mode (default)');
  273. console.log(' \'--release\': will build project for release');
  274. console.log(' \'--nobuild\': will skip build process (useful when using run command)');
  275. console.log(' \'--prepenv\': don\'t build, but copy in build scripts where necessary');
  276. console.log(' \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs.');
  277. console.log(' \'--minSdkVersion=#\': Override minSdkVersion for this build.');
  278. console.log(' \'--maxSdkVersion=#\': Override maxSdkVersion for this build. (Not Recommended)');
  279. console.log(' \'--targetSdkVersion=#\': Override targetSdkVersion for this build.');
  280. console.log(' \'--gradleArg=<gradle command line arg>\': Extra args to pass to the gradle command. Use one flag per arg. Ex. --gradleArg=-PcdvBuildMultipleApks=true');
  281. console.log(' \'--packageType=<apk|bundle>\': Builds an APK or a bundle');
  282. console.log('');
  283. console.log('Signed APK flags (overwrites debug/release-signing.proprties) :');
  284. console.log(' \'--keystore=<path to keystore>\': Key store used to build a signed archive. (Required)');
  285. console.log(' \'--alias=\': Alias for the key store. (Required)');
  286. console.log(' \'--storePassword=\': Password for the key store. (Optional - prompted)');
  287. console.log(' \'--password=\': Password for the key. (Optional - prompted)');
  288. console.log(' \'--keystoreType\': Type of the keystore. (Optional)');
  289. process.exit(0);
  290. };