Repositorio del curso CCOM4030 el semestre B91 del proyecto Paz para la Mujer

build.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var Q = require('q');
  20. var path = require('path');
  21. var shell = require('shelljs');
  22. var superspawn = require('cordova-common').superspawn;
  23. var fs = require('fs');
  24. var plist = require('plist');
  25. var util = require('util');
  26. var check_reqs = require('./check_reqs');
  27. var projectFile = require('./projectFile');
  28. var events = require('cordova-common').events;
  29. // These are regular expressions to detect if the user is changing any of the built-in xcodebuildArgs
  30. /* eslint-disable no-useless-escape */
  31. var buildFlagMatchers = {
  32. 'workspace': /^\-workspace\s*(.*)/,
  33. 'scheme': /^\-scheme\s*(.*)/,
  34. 'configuration': /^\-configuration\s*(.*)/,
  35. 'sdk': /^\-sdk\s*(.*)/,
  36. 'destination': /^\-destination\s*(.*)/,
  37. 'archivePath': /^\-archivePath\s*(.*)/,
  38. 'configuration_build_dir': /^(CONFIGURATION_BUILD_DIR=.*)/,
  39. 'shared_precomps_dir': /^(SHARED_PRECOMPS_DIR=.*)/
  40. };
  41. /* eslint-enable no-useless-escape */
  42. /**
  43. * Creates a project object (see projectFile.js/parseProjectFile) from
  44. * a project path and name
  45. *
  46. * @param {*} projectPath
  47. * @param {*} projectName
  48. */
  49. function createProjectObject (projectPath, projectName) {
  50. var locations = {
  51. root: projectPath,
  52. pbxproj: path.join(projectPath, projectName + '.xcodeproj', 'project.pbxproj')
  53. };
  54. return projectFile.parse(locations);
  55. }
  56. /**
  57. * Gets the resolved bundle identifier from a project.
  58. * Resolves the variable set in INFO.plist, if any (simple case)
  59. *
  60. * @param {*} projectObject
  61. */
  62. function getBundleIdentifier (projectObject) {
  63. var packageName = projectObject.getPackageName();
  64. var bundleIdentifier = packageName;
  65. var variables = packageName.match(/\$\((\w+)\)/); // match $(VARIABLE), if any
  66. if (variables && variables.length >= 2) {
  67. bundleIdentifier = projectObject.xcode.getBuildProperty(variables[1]);
  68. }
  69. return bundleIdentifier;
  70. }
  71. /**
  72. * Returns a promise that resolves to the default simulator target; the logic here
  73. * matches what `cordova emulate ios` does.
  74. *
  75. * The return object has two properties: `name` (the Xcode destination name),
  76. * `identifier` (the simctl identifier), and `simIdentifier` (essentially the cordova emulate target)
  77. *
  78. * @return {Promise}
  79. */
  80. function getDefaultSimulatorTarget () {
  81. return require('./list-emulator-build-targets').run()
  82. .then(function (emulators) {
  83. var targetEmulator;
  84. if (emulators.length > 0) {
  85. targetEmulator = emulators[0];
  86. }
  87. emulators.forEach(function (emulator) {
  88. if (emulator.name.indexOf('iPhone') === 0) {
  89. targetEmulator = emulator;
  90. }
  91. });
  92. return targetEmulator;
  93. });
  94. }
  95. module.exports.run = function (buildOpts) {
  96. var emulatorTarget = '';
  97. var projectPath = path.join(__dirname, '..', '..');
  98. var projectName = '';
  99. buildOpts = buildOpts || {};
  100. if (buildOpts.debug && buildOpts.release) {
  101. return Q.reject('Cannot specify "debug" and "release" options together.');
  102. }
  103. if (buildOpts.device && buildOpts.emulator) {
  104. return Q.reject('Cannot specify "device" and "emulator" options together.');
  105. }
  106. if (buildOpts.buildConfig) {
  107. if (!fs.existsSync(buildOpts.buildConfig)) {
  108. return Q.reject('Build config file does not exist:' + buildOpts.buildConfig);
  109. }
  110. events.emit('log', 'Reading build config file:', path.resolve(buildOpts.buildConfig));
  111. var contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');
  112. var buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOM
  113. if (buildConfig.ios) {
  114. var buildType = buildOpts.release ? 'release' : 'debug';
  115. var config = buildConfig.ios[buildType];
  116. if (config) {
  117. ['codeSignIdentity', 'codeSignResourceRules', 'provisioningProfile', 'developmentTeam', 'packageType', 'buildFlag', 'iCloudContainerEnvironment', 'automaticProvisioning'].forEach(
  118. function (key) {
  119. buildOpts[key] = buildOpts[key] || config[key];
  120. });
  121. }
  122. }
  123. }
  124. return require('./list-devices').run()
  125. .then(function (devices) {
  126. if (devices.length > 0 && !(buildOpts.emulator)) {
  127. // we also explicitly set device flag in options as we pass
  128. // those parameters to other api (build as an example)
  129. buildOpts.device = true;
  130. return check_reqs.check_ios_deploy();
  131. }
  132. }).then(function () {
  133. // CB-12287: Determine the device we should target when building for a simulator
  134. if (!buildOpts.device) {
  135. var newTarget = buildOpts.target || '';
  136. if (newTarget) {
  137. // only grab the device name, not the runtime specifier
  138. newTarget = newTarget.split(',')[0];
  139. }
  140. // a target was given to us, find the matching Xcode destination name
  141. var promise = require('./list-emulator-build-targets').targetForSimIdentifier(newTarget);
  142. return promise.then(function (theTarget) {
  143. if (!theTarget) {
  144. return getDefaultSimulatorTarget().then(function (defaultTarget) {
  145. emulatorTarget = defaultTarget.name;
  146. events.emit('warn', `No simulator found for "${newTarget}. Falling back to the default target.`);
  147. events.emit('log', `Building for "${emulatorTarget}" Simulator (${defaultTarget.identifier}, ${defaultTarget.simIdentifier}).`);
  148. return emulatorTarget;
  149. });
  150. } else {
  151. emulatorTarget = theTarget.name;
  152. events.emit('log', `Building for "${emulatorTarget}" Simulator (${theTarget.identifier}, ${theTarget.simIdentifier}).`);
  153. return emulatorTarget;
  154. }
  155. });
  156. }
  157. }).then(function () {
  158. return check_reqs.run();
  159. }).then(function () {
  160. return findXCodeProjectIn(projectPath);
  161. }).then(function (name) {
  162. projectName = name;
  163. var extraConfig = '';
  164. if (buildOpts.codeSignIdentity) {
  165. extraConfig += 'CODE_SIGN_IDENTITY = ' + buildOpts.codeSignIdentity + '\n';
  166. extraConfig += 'CODE_SIGN_IDENTITY[sdk=iphoneos*] = ' + buildOpts.codeSignIdentity + '\n';
  167. }
  168. if (buildOpts.codeSignResourceRules) {
  169. extraConfig += 'CODE_SIGN_RESOURCE_RULES_PATH = ' + buildOpts.codeSignResourceRules + '\n';
  170. }
  171. if (buildOpts.provisioningProfile) {
  172. extraConfig += 'PROVISIONING_PROFILE = ' + buildOpts.provisioningProfile + '\n';
  173. }
  174. if (buildOpts.developmentTeam) {
  175. extraConfig += 'DEVELOPMENT_TEAM = ' + buildOpts.developmentTeam + '\n';
  176. }
  177. function writeCodeSignStyle (value) {
  178. var project = createProjectObject(projectPath, projectName);
  179. events.emit('verbose', `Set CODE_SIGN_STYLE Build Property to ${value}.`);
  180. project.xcode.updateBuildProperty('CODE_SIGN_STYLE', value);
  181. events.emit('verbose', `Set ProvisioningStyle Target Attribute to ${value}.`);
  182. project.xcode.addTargetAttribute('ProvisioningStyle', value);
  183. project.write();
  184. }
  185. if (buildOpts.provisioningProfile) {
  186. events.emit('verbose', 'ProvisioningProfile build option set, changing project settings to Manual.');
  187. writeCodeSignStyle('Manual');
  188. } else if (buildOpts.automaticProvisioning) {
  189. events.emit('verbose', 'ProvisioningProfile build option NOT set, changing project settings to Automatic.');
  190. writeCodeSignStyle('Automatic');
  191. }
  192. return Q.nfcall(fs.writeFile, path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');
  193. }).then(function () {
  194. var configuration = buildOpts.release ? 'Release' : 'Debug';
  195. events.emit('log', 'Building project: ' + path.join(projectPath, projectName + '.xcworkspace'));
  196. events.emit('log', '\tConfiguration: ' + configuration);
  197. events.emit('log', '\tPlatform: ' + (buildOpts.device ? 'device' : 'emulator'));
  198. events.emit('log', '\tTarget: ' + emulatorTarget);
  199. var buildOutputDir = path.join(projectPath, 'build', (buildOpts.device ? 'device' : 'emulator'));
  200. // remove the build/device folder before building
  201. shell.rm('-rf', buildOutputDir);
  202. var xcodebuildArgs = getXcodeBuildArgs(projectName, projectPath, configuration, buildOpts.device, buildOpts.buildFlag, emulatorTarget, buildOpts.automaticProvisioning);
  203. return superspawn.spawn('xcodebuild', xcodebuildArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });
  204. }).then(function () {
  205. if (!buildOpts.device || buildOpts.noSign) {
  206. return;
  207. }
  208. var project = createProjectObject(projectPath, projectName);
  209. var bundleIdentifier = getBundleIdentifier(project);
  210. var exportOptions = { 'compileBitcode': false, 'method': 'development' };
  211. if (buildOpts.packageType) {
  212. exportOptions.method = buildOpts.packageType;
  213. }
  214. if (buildOpts.iCloudContainerEnvironment) {
  215. exportOptions.iCloudContainerEnvironment = buildOpts.iCloudContainerEnvironment;
  216. }
  217. if (buildOpts.developmentTeam) {
  218. exportOptions.teamID = buildOpts.developmentTeam;
  219. }
  220. if (buildOpts.provisioningProfile && bundleIdentifier) {
  221. exportOptions.provisioningProfiles = { [ bundleIdentifier ]: String(buildOpts.provisioningProfile) };
  222. exportOptions.signingStyle = 'manual';
  223. }
  224. if (buildOpts.codeSignIdentity) {
  225. exportOptions.signingCertificate = buildOpts.codeSignIdentity;
  226. }
  227. var exportOptionsPlist = plist.build(exportOptions);
  228. var exportOptionsPath = path.join(projectPath, 'exportOptions.plist');
  229. var buildOutputDir = path.join(projectPath, 'build', 'device');
  230. function checkSystemRuby () {
  231. var ruby_cmd = shell.which('ruby');
  232. if (ruby_cmd !== '/usr/bin/ruby') {
  233. events.emit('warn', 'Non-system Ruby in use. This may cause packaging to fail.\n' +
  234. 'If you use RVM, please run `rvm use system`.\n' +
  235. 'If you use chruby, please run `chruby system`.');
  236. }
  237. }
  238. function packageArchive () {
  239. var xcodearchiveArgs = getXcodeArchiveArgs(projectName, projectPath, buildOutputDir, exportOptionsPath, buildOpts.automaticProvisioning);
  240. return superspawn.spawn('xcodebuild', xcodearchiveArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });
  241. }
  242. return Q.nfcall(fs.writeFile, exportOptionsPath, exportOptionsPlist, 'utf-8')
  243. .then(checkSystemRuby)
  244. .then(packageArchive);
  245. });
  246. };
  247. /**
  248. * Searches for first XCode project in specified folder
  249. * @param {String} projectPath Path where to search project
  250. * @return {Promise} Promise either fulfilled with project name or rejected
  251. */
  252. function findXCodeProjectIn (projectPath) {
  253. // 'Searching for Xcode project in ' + projectPath);
  254. var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {
  255. return path.extname(name) === '.xcodeproj';
  256. });
  257. if (xcodeProjFiles.length === 0) {
  258. return Q.reject('No Xcode project found in ' + projectPath);
  259. }
  260. if (xcodeProjFiles.length > 1) {
  261. events.emit('warn', 'Found multiple .xcodeproj directories in \n' +
  262. projectPath + '\nUsing first one');
  263. }
  264. var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');
  265. return Q.resolve(projectName);
  266. }
  267. module.exports.findXCodeProjectIn = findXCodeProjectIn;
  268. /**
  269. * Returns array of arguments for xcodebuild
  270. * @param {String} projectName Name of xcode project
  271. * @param {String} projectPath Path to project file. Will be used to set CWD for xcodebuild
  272. * @param {String} configuration Configuration name: debug|release
  273. * @param {Boolean} isDevice Flag that specify target for package (device/emulator)
  274. * @param {Array} buildFlags
  275. * @param {String} emulatorTarget Target for emulator (rather than default)
  276. * @param {Boolean} autoProvisioning Whether to allow Xcode to automatically update provisioning
  277. * @return {Array} Array of arguments that could be passed directly to spawn method
  278. */
  279. function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, buildFlags, emulatorTarget, autoProvisioning) {
  280. var xcodebuildArgs;
  281. var options;
  282. var buildActions;
  283. var settings;
  284. var customArgs = {};
  285. customArgs.otherFlags = [];
  286. if (buildFlags) {
  287. if (typeof buildFlags === 'string' || buildFlags instanceof String) {
  288. parseBuildFlag(buildFlags, customArgs);
  289. } else { // buildFlags is an Array of strings
  290. buildFlags.forEach(function (flag) {
  291. parseBuildFlag(flag, customArgs);
  292. });
  293. }
  294. }
  295. if (isDevice) {
  296. options = [
  297. '-workspace', customArgs.workspace || projectName + '.xcworkspace',
  298. '-scheme', customArgs.scheme || projectName,
  299. '-configuration', customArgs.configuration || configuration,
  300. '-destination', customArgs.destination || 'generic/platform=iOS',
  301. '-archivePath', customArgs.archivePath || projectName + '.xcarchive'
  302. ];
  303. buildActions = [ 'archive' ];
  304. settings = [
  305. customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),
  306. customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
  307. ];
  308. // Add other matched flags to otherFlags to let xcodebuild present an appropriate error.
  309. // This is preferable to just ignoring the flags that the user has passed in.
  310. if (customArgs.sdk) {
  311. customArgs.otherFlags = customArgs.otherFlags.concat(['-sdk', customArgs.sdk]);
  312. }
  313. if (autoProvisioning) {
  314. options = options.concat(['-allowProvisioningUpdates']);
  315. }
  316. } else { // emulator
  317. options = [
  318. '-workspace', customArgs.project || projectName + '.xcworkspace',
  319. '-scheme', customArgs.scheme || projectName,
  320. '-configuration', customArgs.configuration || configuration,
  321. '-sdk', customArgs.sdk || 'iphonesimulator',
  322. '-destination', customArgs.destination || 'platform=iOS Simulator,name=' + emulatorTarget
  323. ];
  324. buildActions = [ 'build' ];
  325. settings = [
  326. customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),
  327. customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
  328. ];
  329. // Add other matched flags to otherFlags to let xcodebuild present an appropriate error.
  330. // This is preferable to just ignoring the flags that the user has passed in.
  331. if (customArgs.archivePath) {
  332. customArgs.otherFlags = customArgs.otherFlags.concat(['-archivePath', customArgs.archivePath]);
  333. }
  334. }
  335. xcodebuildArgs = options.concat(buildActions).concat(settings).concat(customArgs.otherFlags);
  336. return xcodebuildArgs;
  337. }
  338. /**
  339. * Returns array of arguments for xcodebuild
  340. * @param {String} projectName Name of xcode project
  341. * @param {String} projectPath Path to project file. Will be used to set CWD for xcodebuild
  342. * @param {String} outputPath Output directory to contain the IPA
  343. * @param {String} exportOptionsPath Path to the exportOptions.plist file
  344. * @param {Boolean} autoProvisioning Whether to allow Xcode to automatically update provisioning
  345. * @return {Array} Array of arguments that could be passed directly to spawn method
  346. */
  347. function getXcodeArchiveArgs (projectName, projectPath, outputPath, exportOptionsPath, autoProvisioning) {
  348. return [
  349. '-exportArchive',
  350. '-archivePath', projectName + '.xcarchive',
  351. '-exportOptionsPlist', exportOptionsPath,
  352. '-exportPath', outputPath
  353. ].concat(autoProvisioning ? ['-allowProvisioningUpdates'] : []);
  354. }
  355. function parseBuildFlag (buildFlag, args) {
  356. var matched;
  357. for (var key in buildFlagMatchers) {
  358. var found = buildFlag.match(buildFlagMatchers[key]);
  359. if (found) {
  360. matched = true;
  361. // found[0] is the whole match, found[1] is the first match in parentheses.
  362. args[key] = found[1];
  363. events.emit('warn', util.format('Overriding xcodebuildArg: %s', buildFlag));
  364. }
  365. }
  366. if (!matched) {
  367. // If the flag starts with a '-' then it is an xcodebuild built-in option or a
  368. // user-defined setting. The regex makes sure that we don't split a user-defined
  369. // setting that is wrapped in quotes.
  370. /* eslint-disable no-useless-escape */
  371. if (buildFlag[0] === '-' && !buildFlag.match(/^.*=(\".*\")|(\'.*\')$/)) {
  372. args.otherFlags = args.otherFlags.concat(buildFlag.split(' '));
  373. events.emit('warn', util.format('Adding xcodebuildArg: %s', buildFlag.split(' ')));
  374. } else {
  375. args.otherFlags.push(buildFlag);
  376. events.emit('warn', util.format('Adding xcodebuildArg: %s', buildFlag));
  377. }
  378. }
  379. }
  380. // help/usage function
  381. module.exports.help = function help () {
  382. console.log('');
  383. console.log('Usage: build [--debug | --release] [--archs=\"<list of architectures...>\"]');
  384. console.log(' [--device | --simulator] [--codeSignIdentity=\"<identity>\"]');
  385. console.log(' [--codeSignResourceRules=\"<resourcerules path>\"]');
  386. console.log(' [--developmentTeam=\"<Team ID>\"]');
  387. console.log(' [--provisioningProfile=\"<provisioning profile>\"]');
  388. console.log(' --help : Displays this dialog.');
  389. console.log(' --debug : Builds project in debug mode. (Default)');
  390. console.log(' --release : Builds project in release mode.');
  391. console.log(' -r : Shortcut :: builds project in release mode.');
  392. /* eslint-enable no-useless-escape */
  393. // TODO: add support for building different archs
  394. // console.log(" --archs : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");
  395. console.log(' --device, --simulator');
  396. console.log(' : Specifies, what type of project to build');
  397. console.log(' --codeSignIdentity : Type of signing identity used for code signing.');
  398. console.log(' --codeSignResourceRules : Path to ResourceRules.plist.');
  399. console.log(' --developmentTeam : New for Xcode 8. The development team (Team ID)');
  400. console.log(' to use for code signing.');
  401. console.log(' --provisioningProfile : UUID of the profile.');
  402. console.log(' --device --noSign : Builds project without application signing.');
  403. console.log('');
  404. console.log('examples:');
  405. console.log(' build ');
  406. console.log(' build --debug');
  407. console.log(' build --release');
  408. console.log(' build --codeSignIdentity="iPhone Distribution" --provisioningProfile="926c2bd6-8de9-4c2f-8407-1016d2d12954"');
  409. // TODO: add support for building different archs
  410. // console.log(" build --release --archs=\"armv7\"");
  411. console.log('');
  412. process.exit(0);
  413. };