1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 | 1× 1× 1× 1× 1× 43× 1× 2× 1× 3× 3× 1× 1× 1× 1× 1× 1× 1× 72× 1× 1× 1× 1× 1× 1× 1× 3× 3× 3× 3× 1× 2× 2× 1× 20× 1× 15× 1× 1× 1× 1× 1× 7× 1× 3× 1× 4× 1× 1× 1× 1× 3× 3× 3× 1× 1× 2× 2× 2× 2× 1× 2× 2× 2× 2× 3× 3× 2× 3× 3× 3× 1× 1× 1× 3× 3× 3× 3× 3× 1× 1× 1× 3× 3× 1× 1× 3× 3× 3× 3× 1× 1× 3× 2× 1× 1× 3× 1× 43× 43× 43× 43× 43× 43× 1× 1× 14× 14× 25× 25× 17× 17× 4× 17× 2× 2× 17× 14× 1× 13× 13× 13× 19× 19× 19× 4× 4× 19× 9× 9× 6× 9× 10× 8× 13× 1× 8× 8× 8× 8× 1× 7× 1× 6× 8× 6× 6× 6× 6× 6× 8× 1× 1× 1× 1× 1× 2× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 8× 8× 8× 8× 79× 8× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 11× 1× 1× 1× 1× 2× 2× 2× 1× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 1× 2× 1× 3× 1× 1× 1× 1× 1× 2× 2× 2× 1× 1× 1× 1× 1× 2× 2× 1× 4× 4× 2× 1× 5× 5× 3× 3× 1× 5× 1× 6× 1× 5× 1× 4× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× | // jscs:disable jsDoc /** * This code is closed source and Confidential and Proprietary to * Appcelerator, Inc. All Rights Reserved. This code MUST not be * modified, copied or otherwise redistributed without express * written permission of Appcelerator. This file is licensed as * part of the Appcelerator Platform and governed under the terms * of the Appcelerator license agreement. */ var fs = require('fs'), path = require('path'), os = require('os'), chalk, urllib = require('url'), PacAgent = require('pac-proxy-agent'), semver = require('semver'), debug = require('debug')('appc:util'), spinner, spriteIndex = 0, cachedConfig, sprite = '/-\\|', execSync = require('child_process').execSync; var MAX_RETRIES = exports.MAX_RETRIES = 5; var CONN_TIMEOUT = 10000; //NOTE: not using char-spinner because i don't want it to reset to beginning //of line each time it starts/stops. i want to spin in place at point of cursor /* Testing Utilities. */ exports.stdout = process.stdout; /* istanbul ignore next */ exports.exit = function (code) { process.exit(code); }; /* istanbul ignore next */ exports.setCachedConfig = function (val) { cachedConfig = val; }; /** * start the spinner */ function startSpinner() { stopSpinner(); if (!spinner && exports.stdout.isTTY && !process.env.TRAVIS) { var count = 0; spinner = setInterval(function () { Iif (count++ > 0) { // go back one column exports.stdout.write('\033[1D'); } var s = ++spriteIndex % sprite.length; var c = sprite[s]; exports.stdout.write(c); }, 50); } } /** * stop the spinner */ function stopSpinner() { if (spinner) { clearInterval(spinner); // go back on column exports.stdout.write('\033[1D'); spinner = null; } } /** * write a wait message and start spinner */ function waitMessage(msg) { exports.stdout.write(msg); startSpinner(); } /** * write OK mark and stop spinner */ function okMessage(msg) { chalk = chalk || require('chalk'); stopSpinner(); msg = msg || ''; exports.stdout.write(msg + ' ' + chalk.green(isWindows() ? 'OK' : '✓') + '\n'); } /** * write message and stop spinner */ function infoMessage(msg) { stopSpinner(); exports.stdout.write(msg + '\n'); } /** * return the platform specific HOME directory */ function getHomeDir() { return os.homedir(); } /** * return our AppC directory */ function getAppcDir() { return path.join(getHomeDir(), '.appcelerator'); } /** * return the AppC install tag file */ function getInstallTag() { return path.join(getAppcDir(), '.installing'); } /** * return the global cache directory in the users home folder */ function getCacheDir() { return path.join(getAppcDir(), 'cache'); } /** * return the platform specific install directory */ function getInstallDir() { return path.join(getAppcDir(), 'install'); } /** * return the version file */ function getVersionFile() { return path.join(getInstallDir(), '.version'); } /** * return the config file */ function getConfigFile() { return path.join(getAppcDir(), 'appc-cli.json'); } /** * return the private npm cache directory */ function getNpmCacheDirectory() { return path.join(getAppcDir(), '.npm'); } /** * write out the current version file */ function writeVersion(version) { var versionFile = getVersionFile(); debug('writing version: %s to %s', version, versionFile); if (fs.existsSync(versionFile)) { fs.unlinkSync(versionFile); } fs.writeFileSync(versionFile, version); } /** * return the active version (if specified) or undefined */ function getActiveVersion() { var versionFile = getVersionFile(); Eif (fs.existsSync(versionFile)) { return fs.readFileSync(versionFile).toString().trim(); } } /** * remove version file */ function removeVersion() { var versionFile = getVersionFile(); debug('remove version %s', versionFile); if (fs.existsSync(versionFile)) { fs.unlinkSync(versionFile); } } /** * list versions installed */ function listVersions(opts, versions) { chalk = chalk || require('chalk'); Iif (!versions) { exports.stdout.write(chalk.red('No versions available') + '\n'); return; } var activeVersion = getActiveVersion(); // If we don't find latest version from api/appc/list endpoint, then inject the latest version into the list. var versionsList = Object.keys(versions).map(function (value, index) { return versions[index].version || versions[index]; }); Eif (opts.latest && versionsList.indexOf(opts.latest) === -1) { versionsList.push(opts.latest); } versions = versionsList.sort(semver.compareLoose); versions.forEach(function (entry) { var ver = entry.version ? entry.version : entry, suffix = getInstallBinary(opts, ver) ? 'Installed' : 'Not Installed'; if (opts.latest === ver) { suffix += chalk.white.bold(' (Latest)'); } Iif (activeVersion && activeVersion === ver) { suffix += chalk.red(' (Active)'); } var date = entry.date ? ' ' + chalk.grey(pad(new Date(Date.parse(entry.date)), 15)) : ''; exports.stdout.write(chalk.yellow(pad(ver, 10)) + ' ' + chalk.cyan(pad(suffix, 40)) + date + '\n'); }); } /** * return json object of versions */ function getVersionJson(opts, versions) { var activeVersion = getActiveVersion(), obj = { versions: [], installed: getInstalledVersions(), latest: opts.latest, active: activeVersion }; if (Array.isArray(versions)) { if (versions[0] && versions[0].version) { obj.versions = Object.keys(versions).map(function (value, index) { return versions[index].version; }); } else { obj.versions = versions; } } return obj; } /** * return the current versions installed */ function getInstalledVersions(callback) { var installDir = getInstallDir(); if (fs.existsSync(installDir)) { // try and resolve the latest try { var dirs = fs.readdirSync(installDir); if (dirs.length) { if (dirs.length > 1) { // attempt to sort by latest version dirs = dirs.filter(function (e) { return e[0] !== '.'; }).sort(function (a, b) { var av = parseInt(a.replace(/\./g, '')), bv = parseInt(b.replace(/\./g, '')); return bv - av; }); } debug('found the following version directories: %j', dirs); return dirs; } } catch (E) { debug('error reading install directory %o', E); if (E.code === 'EACCES') { chalk = chalk || require('chalk'); var chPer = 'Please make sure you change the permissions and re-try'; var chPerWithCmds = 'Please make sure you change the permissions using these commands:\n\n\t'; chPerWithCmds += chalk.yellow('sudo chown -R ' + process.env.USER + ' ' + installDir + '\n\tchmod -R 0700 ' + installDir); var message = process.platform === 'win32' ? chPer : chPerWithCmds + '\n'; fail('Ooops! Your install directory (' + installDir + ') is not writable.\n' + message); } fail(E); } } } /** * return the platform specific install binary path */ function getInstallBinary(opts, theversion) { opts = opts || {}; // first check and see if specified on command line as option var version = theversion || (opts.version !== true ? opts.version : null) || '', installDir = getInstallDir(), bin = path.join(installDir, version, 'package', 'bin', 'appc'), pkg, dirs; Iif (fs.existsSync(bin)) { // check the package.json since we will delete it on an interrupted download attempt pkg = path.join(installDir, version, 'package', 'package.json'); return fs.existsSync(pkg) && bin; } else Eif (theversion) { // if we specified a version and we didn't find it, return null return null; } // see if we have a version set theversion = getActiveVersion(); if (theversion) { bin = getInstallBinary(opts, theversion); if (!bin) { if (!opts.version) { chalk = chalk || require('chalk'); debug('you have specified a version (%s) that isn\'t found', theversion); // only warn if we're not asking for this version // invalid version specified in version file. remove it and then re-install from latest exports.stdout.write(chalk.red('version ' + theversion + ' specified previously is no longer available.') + '\n'); } removeVersion(); } else { return bin; } } dirs = getInstalledVersions(); if (dirs) { for (var c = 0; c < dirs.length; c++) { bin = path.join(installDir, dirs[c], 'package', 'bin', 'appc'); if (fs.existsSync(bin)) { // check the package.json since we will delete it on an interrupted download attempt pkg = path.join(installDir, dirs[c], 'package', 'package.json'); return fs.existsSync(pkg) && bin; } } } } /** * given a full path, makes sure that the directory exists */ function ensureDir(dir) { var last = expandPath(dir), parts = []; // find the top of the root that exists do { parts.unshift(path.basename(last)); last = path.join(last, '..'); } while (!fs.existsSync(last)); Iif (!fs.existsSync(last)) { fs.mkdirSync(last); } // now create the directories in order for (var c = 0; c < parts.length; c++) { var fp = path.join(last, parts[c]); Eif (!fs.existsSync(fp)) { fs.mkdirSync(fp); } last = fp; } return dir; } /** * expand ~ in fn */ function expandPath(fn) { var home = getHomeDir(), p = fn.replace(/~\/?/g, function (value) { if (/\/$/.test(value)) { return home + '/'; } return home; }); return p; } /** * fail and properly exit */ function fail(msg) { stopSpinner(); debug('fail %o', msg); Iif (msg.stack && process.env.DEBUG) { console.error(msg.stack); } chalk = chalk || require('chalk'); console.error('\n' + (chalk.red(msg.message || msg))); exports.exit(1); } var optionRE = /^-{1,2}([\w-_]+)=?(.*)?$/; /** * very loose parsing of options */ function parseOpts() { var args = {}; for (var c = 2; c < process.argv.length; c++) { var arg = process.argv[c]; if (optionRE.test(arg)) { var match = optionRE.exec(arg), name = match[1], value = match.length > 2 && match[2] || (process.argv[c + 1] && !/^-{1,2}/.test(process.argv[c + 1]) ? process.argv[c + 1] : null) || true; if (value === 'true' || value === 'false') { value = value === 'true'; } if (name.indexOf('no-') === 0) { name = name.substring(3); value = false; } args[name] = value; } } return args; } /** * loose parse none options */ function parseArgs(opts) { Iif (!opts) { throw new Error('missing opts'); } var args = []; for (var c = 2; c < process.argv.length; c++) { var arg = process.argv[c]; var previous = process.argv[c - 1]; if (optionRE.test(previous)) { var previousMatch = optionRE.exec(previous); previous = previousMatch[1]; } if (optionRE.test(arg)) { var match = optionRE.exec(arg), name = match[1], value = opts[name]; // see if a value was provided and if so, remove it too if (value && String(process.argv[c + 1] === String(value))) { c++; } continue; } else if (opts[previous] === undefined) { args.push(arg); } } return args; } /** * make a registry url */ function makeURL(opts, urlpath) { Iif (typeof(opts) === 'string') { urlpath = opts; opts = {}; } else { opts = opts || {}; } var baseurl; if (opts.registry) { baseurl = opts.registry; } else if (process.env.APPC_REGISTRY_SERVER) { baseurl = process.env.APPC_REGISTRY_SERVER; } else Iif (process.env.APPC_ENV || process.env.NODE_ENV) { var env = process.env.APPC_ENV || process.env.NODE_ENV; if (env === 'preproduction') { baseurl = DEFAULT_PREPROD_REGISTRY_URL; } else if (env === 'preprodonprod') { baseurl = DEFAULT_PREPRODONPROD_REGISTRY_URL; } else if (env === 'production') { baseurl = DEFAULT_PROD_REGISTRY_URL; } } if (!baseurl) { var config = readConfig(); Iif (config && config.registry) { baseurl = config.registry; } else Iif (config && (config.defaultEnvironment === 'preproduction' || config.environmentName === 'preproduction')) { baseurl = DEFAULT_PREPROD_REGISTRY_URL; } else Iif (config && (config.defaultEnvironment === 'preprodonprod' || config.environmentName === 'preprodonprod')) { baseurl = DEFAULT_PREPRODONPROD_REGISTRY_URL; } else { baseurl = DEFAULT_PROD_REGISTRY_URL; } } return urllib.resolve(baseurl, urlpath); } function makeRequestError(msg, code) { var err = new Error(msg); err.code = code; return err; } // TODO: Perhaps we should include and use appc-platform-sdk env vars? var DEFAULT_PREPROD_REGISTRY_URL = ' https://registry.axwaytest.net'; var DEFAULT_PROD_REGISTRY_URL = 'https://registry.platform.axway.com'; var DEFAULT_PREPRODONPROD_REGISTRY_URL = 'https://software-preprodonprod.appcelerator.com'; /** * return the request library */ function getRequest() { return require('request'); } /** * make a request to location url */ function request(location, callback) { var options; Iif (typeof(location) === 'object') { options = location; location = options.url; } var url = urllib.parse(location), config = readConfig(), userAgent = 'Appcelerator CLI/' + require('../package').version + ' (' + process.platform + ')', opts = { url: url, headers: { 'user-agent': userAgent, host: url.host, 'appc-token': config && config.sid } }; Iif (options) { opts.timeout = CONN_TIMEOUT * (options.attempts || 1); } Iif (process.env.APPC_CONFIG_PAC_FILE) { opts.agent = new PacAgent('pac+' + process.env.APPC_CONFIG_PAC_FILE); } else Eif (process.env.APPC_CONFIG_PROXY !== '') { opts.proxy = process.env.APPC_CONFIG_PROXY; } Iif (process.env.APPC_CONFIG_CAFILE) { opts.ca = fs.readFileSync(process.env.APPC_CONFIG_CAFILE, 'utf8'); } Iif (process.env.APPC_CONFIG_STRICTSSL === 'false') { opts.strictSSL = false; } var req = getRequest().get(opts); debug('request %j', opts); // start the request req.on('response', function (res) { debug('request response received'); Iif (req.__err) { debug('request response callback skipped, request error already executed.'); } else { callback(null, res, req); } }); // check the error req.on('error', function (err) { req.__err = true; debug('request error', err); if (err.name === 'AppCError') { return callback(err); } if (err.code === 'ECONNREFUSED') { return callback(makeRequestError('Error connecting to download server at ' + url.host + '. Make sure you are online.', err.code)); } else if (err.code === 'ENOTFOUND') { return callback(makeRequestError('Error connecting to download server at ' + url.host + ' (not found). Make sure you are online.', err.code)); } else if (err.code === 'ECONNRESET') { return callback(makeRequestError('Error connecting to download server at ' + url.host + ' (reset). Make sure you are online.', err.code)); } return callback(err); }); return req; } /** * make a request a return JSON */ function requestJSON(location, callback, attempts) { return request(location, function (err, res, req) { attempts = attempts || 1; if (typeof(location) === 'object') { location.attempts = attempts + 1; } debug('connection attempt %d of %d', attempts, MAX_RETRIES); if (err) { if (err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET' || err.code === 'ETIMEDOUT' || err.message.indexOf('hang up') > 0) { debug('connection error %s with message %s', err.code, err.message); // retry again if (attempts >= MAX_RETRIES) { return callback(err); } return setTimeout(function () { return requestJSON(location, callback, attempts + 1); }, 500 * attempts); } return callback(err); } if (res && req.headers && req.headers['content-type'] && req.headers['content-type'].indexOf('/json') < 0) { debug('response status code: %d with headers: %j', res.statusCode, res.headers); // retry again if (attempts >= MAX_RETRIES) { return callback(err); } return setTimeout(function () { return requestJSON(location, callback, attempts + 1); }, 500 * attempts); } if (res.statusCode === 200) { debug('response status code: %d with headers: %j', res.statusCode, res.headers); var buf = ''; res.on('data', function (chunk) { buf += chunk; }); res.on('end', function () { debug('attempting to parse JSON => [%s]', buf); callback(null, JSON.parse(buf)); }); res.on('error', callback); } else if (res.statusCode === 301 || res.statusCode === 302) { debug('response status code: %d with headers: %j', res.statusCode, res.headers); return requestJSON(res.headers.location, callback); } else if (res && /^(400|404|408|500|502|503|504)$/.test(String(res.statusCode))) { debug('response status code: %d with headers: %j', res.statusCode, res.headers); attempts = attempts || 1; if (attempts >= MAX_RETRIES) { return callback(err); } return setTimeout(function () { return requestJSON(location, callback, attempts + 1); }, 500 * attempts); } else { return callback(new Error('Invalid response code: ' + res.statusCode + ' received from server.')); } }); } /** * right pad a string to a specific length */ function pad(str, len) { chalk = chalk || require('chalk'); var slen = chalk.stripColor(str).length; var newstr = str; for (var c = slen; c < len; c++) { newstr += ' '; } return newstr; } /** * returns true if directory is writable by user */ function canWriteDir(dir) { var del = !fs.existsSync(dir), fn; try { if (del) { ensureDir(dir); } if (fs.statSync(dir).isDirectory()) { // create a temp file -- seems like the best way to handle cross platform fn = path.join(dir, String(+new Date()) + (Math.random() * 3) + '.txt'); // console.log(fn); fs.writeFileSync(fn, 'hi'); return true; } else { // not a directory but a file, sorry... return false; } } catch (E) { if (E.code === 'EACCES') { return false; } console.log(E.stack, E.code); } finally { if (fs.existsSync(fn)) { try { fs.unlinkSync(fn); } catch (ig) {} } if (del) { try { fs.unlinkSync(path); } catch (ig) {} } } } /** * if not writable, returns a message otherwise undefined */ function checkDirectory(dir, name) { var message; var errorlib = require('./error'), chalk = chalk || require('chalk'); if (!canWriteDir(dir)) { var chPer = 'Please make sure you change the permissions and re-try'; var chPerWithCmd = 'Please make sure you change the permissions using these commands:\n\n\t'; chPerWithCmd += chalk.yellow('sudo chown -R ' + process.env.USER + ' ' + dir + '\n\tchmod -R 0700 ' + dir); message = process.platform === 'win32' ? chPer : chPerWithCmd + '\n'; return errorlib.createError('com.appcelerator.install.preflight.directory.unwritable', name, dir, message); } else { // check the ownership of the directory too if (process.platform !== 'win32') { var stat = fs.statSync(dir); if (stat.uid !== process.getuid()) { message = 'Please make sure you change the permissions using these commands:\n\n\t' + chalk.yellow('sudo chown -R ' + process.env.USER + ' ' + dir + '\n\tchmod -R 0700 ' + dir) + '\n'; return errorlib.createError('com.appcelerator.install.preflight.directory.ownership', name, dir, process.env.USER, message); } } } } function abortMessage(name) { // clear line and reset it Eif (exports.stdout.isTTY) { stopSpinner(); exports.stdout.clearLine(); exports.stdout.cursorTo(0); } exports.stdout.write(name + ' aborted.\n'); exports.exit(1); } function readConfig() { if (cachedConfig) { return cachedConfig; } var cf = getConfigFile(); Iif (!fs.existsSync(cf)) { return null; } return (cachedConfig = JSON.parse(fs.readFileSync(cf))); } function writeConfig(config) { cachedConfig = config; var cf = getConfigFile(); fs.writeFileSync(cf, JSON.stringify(config, null, 2)); } /** * perform an update check to see if we have a new version * * however, some rules: * * - don't check each time * - if specifying a version, skip * - if specifying --quiet, skip * - if no config, skip * - if any failure in checking, skip * - only do it once per day (or what is configured) * */ function updateCheck(opts, callback) { // we are specifying a version or we want quiet output, skip Iif (opts.version || opts.quiet || opts.output === 'json') { return callback(); } // check to see if we have a config file and if we don't that's OK, return // since we are in a setup/install var config = readConfig(); Iif (!config) { return callback(); } chalk = chalk || require('chalk'); try { var check = config.lastUpdateCheck; var checkEveryMS = config.updateCheckInterval || 86400000; // once per day in MS Eif (!check || check + checkEveryMS < Date.now()) { // do the check below debug('update check skipping, %d, %d', check, checkEveryMS); } else { // don't do the check return callback(); } } catch (E) { // ignore errors, they will be dealt with otherwise return callback(); } var url = makeURL(opts, '/api/appc/list'); exports.requestJSON(url, function (err, result) { // skip failures Eif (!err && result) { try { var activeVersion = exports.getActiveVersion(), resultList = result.key && result[result.key], latest = result.latest || (resultList && (resultList.length > 0) && resultList[0].version); debug('update check completed, latest is %s', latest); // set the update check timestamp config.lastUpdateCheck = Date.now(); // write out our config writeConfig(config); // see if we have it already var found = exports.getInstallBinary(opts, latest); // if not, inform the user of the update debug('update check found %s', found); if (!found && semver.lt(activeVersion, latest)) { exports.stdout.write('A new update ' + chalk.yellow('(' + latest + ')') + ' is available... Download with ' + chalk.green('appc use ' + latest) + '\n'); } } catch (E) { } } callback(); }); } function isWindows() { return process.platform === 'win32'; } /** * if a TTY is connected, clear all text on the line and reset the * cursor to the beginning of the line */ function resetLine() { Eif (exports.stdout.isTTY) { exports.stdout.clearLine(); exports.stdout.cursorTo(0); } } /** * rmdirSyncRecursive method borrowed from wrench * * The MIT License * * Copyright (c) 2010 Ryan McGrath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ function rmdirSyncRecursive(_path, failSilent) { var files; try { files = fs.readdirSync(_path); } catch (err) { Iif (failSilent) { return; } throw new Error(err.message); } /* Loop through and delete everything in the sub-tree after checking it */ for (var i = 0; i < files.length; i++) { var file = path.join(_path, files[i]); var currFile = fs.lstatSync(file); if (currFile.isDirectory()) { // Recursive function back to the beginning rmdirSyncRecursive(file); } else if (currFile.isSymbolicLink()) { // Unlink symlinks if (isWindows()) { fs.chmodSync(file, 666); // Windows needs this unless joyent/node#3006 is resolved.. } fs.unlinkSync(file); } else { // Assume it's a file - perhaps a try/catch belongs here? if (isWindows) { fs.chmodSync(file, 666); // Windows needs this unless joyent/node#3006 is resolved.. } fs.unlinkSync(file); } } /* Now that we know everything in the sub-tree has been deleted, we can delete the main directory. Huzzah for the shopkeep. */ return fs.rmdirSync(_path); } /** * return an array of arguments appending any subsequent process args */ function mergeOptsToArgs(args, opts) { var argv = [].concat(process.__argv.slice(3)); if (argv.length) { for (var c = 0; c < argv.length; c++) { var arg = argv[c]; args.push(arg); } } return args; } /** * returns the proxy to use, checks: * 1. proxyServer setting from config * 2. environmental variables (HTTP_PROXY, HTTPS_PROXY) * * to set proxyServer value: * appc config set proxyServer '[proxy url]' */ function getProxyServer(config) { var proxy = null, parsed; if (config && config.proxyServer) { parsed = urllib.parse(config.proxyServer); if (/^https?\:$/.test(parsed.protocol) && parsed.hostname && parsed.hostname !== 'null') { proxy = config.proxyServer; } } return proxy || process.env.HTTP_PROXY || process.env.http_proxy || process.env.HTTPS_PROXY || process.env.https_proxy || ''; } /** * return whether or not to do SSL key validation when making https requests. * * to set stricSSL value: * appc config set strictSSL [false/true] */ function getStrictSSL(config) { return config ? config.strictSSL : null; } /** * return the path to a file containing one or multiple Certificate Authority signing certificates. * * to set cafile value: * appc config set cafile '[file path, in PEM format]' */ function getCAfile(config) { if (config && config.cafile && fs.existsSync(config.cafile)) { return config.cafile; } return null; } /** * write out the process.versions info stored when installing package */ function writeVersions(pkgDir) { var versionsFile = path.join(pkgDir, '.nodeversions'), versions = process.versions, versionsStr = JSON.stringify(versions); debug('writing node version: %s to %s', versionsStr, versionsFile); if (fs.existsSync(versionsFile)) { fs.unlinkSync(versionsFile); } fs.writeFileSync(versionsFile, versionsStr); // remove old file var oldVersionFile = path.join(pkgDir, '.nodeversion'); if (fs.existsSync(oldVersionFile)) { fs.unlinkSync(oldVersionFile); } } /** * return the process.versions info when install the package */ function readVersions(installBin) { var versionFile = path.join(installBin, '..', '..', '..', '.nodeversions'), versions; if (fs.existsSync(versionFile)) { try { versions = JSON.parse(fs.readFileSync(versionFile)); } catch (e) { debug('unable to read versions file.'); } return versions; } } /** * check if the minor/major NodeJS version changed since the package was installed */ function isNodeVersionChanged(installBin) { var version = getPackageNodeVersion(installBin), usedNode = version && version.split('.'), currentNode = process.version.split('.'), result = false; if (usedNode && usedNode.length >= 2 && currentNode.length >= 2) { result = !(usedNode[0] === currentNode[0] && usedNode[1] === currentNode[1]); } debug('node used %s, current version %s, result: %s', usedNode, currentNode, result); return result; } /** * check if the modules version changed since the package was installed */ function isModuleVersionChanged(installBin) { var versions = readVersions(installBin), usedVersion = versions && versions.modules, currentModuleVersion = process.versions && process.versions.modules, result = false; if (usedVersion && currentModuleVersion) { result = (usedVersion !== currentModuleVersion); debug('modules version used %s, current version %s, result: %s', usedVersion, currentModuleVersion, result); } else { result = isNodeVersionChanged(installBin); } return result; } /** * return the NodeJS version used to install the package */ function getPackageNodeVersion(installBin) { var versions = readVersions(installBin), usedNodeVersion = versions && versions.node; if (usedNodeVersion) { return usedNodeVersion; } var versionFile = path.join(installBin, '..', '..', '..', '.nodeversion'); if (fs.existsSync(versionFile)) { return fs.readFileSync(versionFile).toString().trim(); } } function outputInfo(msg, isJSON) { if (isJSON) { return; } exports.stdout.write(msg); } function killDaemon(version, installBin) { var pkgFile = path.join(getInstallDir(), version, 'package', 'package.json'); var pkg = fs.existsSync(pkgFile) && require(pkgFile); if (isWindows()) { installBin = '"' + process.execPath + '" "' + installBin + '"'; } if (pkg && 'appcd' in pkg.dependencies) { debug('stop appcd'); try { execSync(installBin + ' appcd stop'); } catch (error) { // ignore debug('error killing the daemon'); debug(error); } } } exports.getAppcDir = getAppcDir; exports.getHomeDir = getHomeDir; exports.getCacheDir = getCacheDir; exports.getConfigFile = getConfigFile; exports.getNpmCacheDirectory = getNpmCacheDirectory; exports.ensureDir = ensureDir; exports.expandPath = expandPath; exports.getInstallDir = getInstallDir; exports.listVersions = listVersions; exports.getVersionJson = getVersionJson; exports.getInstalledVersions = getInstalledVersions; exports.getInstallBinary = getInstallBinary; exports.fail = fail; exports.parseOpts = parseOpts; exports.parseArgs = parseArgs; exports.writeVersion = writeVersion; exports.getActiveVersion = getActiveVersion; exports.makeURL = makeURL; exports.request = request; exports.requestJSON = requestJSON; exports.pad = pad; exports.waitMessage = waitMessage; exports.okMessage = okMessage; exports.infoMessage = infoMessage; exports.stopSpinner = stopSpinner; exports.startSpinner = startSpinner; exports.canWriteDir = canWriteDir; exports.checkDirectory = checkDirectory; exports.abortMessage = abortMessage; exports.updateCheck = updateCheck; exports.isWindows = isWindows; exports.resetLine = resetLine; exports.rmdirSyncRecursive = rmdirSyncRecursive; exports.getRequest = getRequest; exports.mergeOptsToArgs = mergeOptsToArgs; exports.getInstallTag = getInstallTag; exports.getProxyServer = getProxyServer; exports.getStrictSSL = getStrictSSL; exports.getCAfile = getCAfile; exports.readConfig = readConfig; exports.writeVersions = writeVersions; exports.isModuleVersionChanged = isModuleVersionChanged; exports.getPackageNodeVersion = getPackageNodeVersion; exports.outputInfo = outputInfo; exports.killDaemon = killDaemon; |