Code coverage report for lib/common/services/commands-service.js

Statements: 41.26% (85 / 206)      Branches: 21.7% (23 / 106)      Functions: 39.02% (16 / 41)      Lines: 43.08% (84 / 195)      Ignored: none     

All files » lib/common/services/ » commands-service.js
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    1 1 1 1 1       1   1 1 26 26 26 26 26 26 26 26 26 26 26   1       1 8 8 8 8 6 6 6 6   6   6                     6   5 5       5   2     1 11 11   1 35 35   1 23 23 23 23 23   23   1 23 23 23 12     11 11 11         1 23 23 23 23 23 23     23 23                                           1                                             1                                                         1                                                     1                                                                                             1 5 5 5     5     1 11     11   1 1 1 1   1 1  
///<reference path="../.d.ts"/>
"use strict";
var jaroWinklerDistance = require("../vendor/jaro-winkler_distance");
var helpers = require("../helpers");
var os_1 = require("os");
var CommandArgumentsValidationHelper = (function () {
    function CommandArgumentsValidationHelper(isValid, _remainingArguments) {
        this.isValid = isValid;
        this.remainingArguments = _remainingArguments.slice();
    }
    return CommandArgumentsValidationHelper;
})();
var CommandsService = (function () {
    function CommandsService($commandsServiceProvider, $errors, $fs, $hooksService, $injector, $logger, $options, $resources, $staticConfig) {
        this.$commandsServiceProvider = $commandsServiceProvider;
        this.$errors = $errors;
        this.$fs = $fs;
        this.$hooksService = $hooksService;
        this.$injector = $injector;
        this.$logger = $logger;
        this.$options = $options;
        this.$resources = $resources;
        this.$staticConfig = $staticConfig;
        this.areDynamicSubcommandsRegistered = false;
        this.cachedCommandHelp = null;
    }
    CommandsService.prototype.allCommands = function (opts) {
        var commands = this.$injector.getRegisteredCommandsNames(opts.includeDevCommands);
        return _.reject(commands, function (command) { return _.contains(command, '|'); });
    };
    CommandsService.prototype.executeCommandUnchecked = function (commandName, commandArguments) {
        var _this = this;
        return (function () {
            var command = _this.$injector.resolveCommand(commandName);
            if (command) {
                Eif (!_this.$staticConfig.disableAnalytics && !command.disableAnalytics) {
                    var analyticsService = _this.$injector.resolve("analyticsService");
                    Eif (!command.disableAnalyticsConsentCheck) {
                        analyticsService.checkConsent().wait();
                    }
                    analyticsService.trackFeature(commandName).wait();
                }
                Iif (!_this.$staticConfig.disableHooks && (command.enableHooks === undefined || command.enableHooks === true)) {
                    var hierarchicalCommandName = _this.$injector.buildHierarchicalCommand(commandName, commandArguments);
                    if (hierarchicalCommandName) {
                        commandName = helpers.stringReplaceAll(hierarchicalCommandName.commandName, CommandsService.HIERARCHICAL_COMMANDS_DEFAULT_COMMAND_DELIMITER, CommandsService.HOOKS_COMMANDS_DELIMITER);
                        commandName = helpers.stringReplaceAll(commandName, CommandsService.HIERARCHICAL_COMMANDS_DELIMITER, CommandsService.HOOKS_COMMANDS_DELIMITER);
                    }
                    _this.$hooksService.executeBeforeHooks(commandName).wait();
                    command.execute(commandArguments).wait();
                    _this.$hooksService.executeAfterHooks(commandName).wait();
                }
                else {
                    command.execute(commandArguments).wait();
                }
                var commandHelp = _this.getCommandHelp().wait();
                Iif (!command.disableCommandHelpSuggestion && commandHelp && commandHelp[commandName]) {
                    var suggestionText = commandHelp[commandName];
                    _this.$logger.printMarkdown(~suggestionText.indexOf('%s') ? require('util').format(suggestionText, commandArguments) : suggestionText);
                }
                return true;
            }
            return false;
        }).future()();
    };
    CommandsService.prototype.printHelp = function (commandName) {
        this.$options.help = true;
        return this.executeCommandUnchecked("help", [this.beautifyCommandName(commandName)]);
    };
    CommandsService.prototype.executeCommandAction = function (commandName, commandArguments, action) {
        var _this = this;
        return this.$errors.beginCommand(function () { return action.apply(_this, [commandName, commandArguments]); }, function () { return _this.printHelp(commandName); });
    };
    CommandsService.prototype.tryExecuteCommandAction = function (commandName, commandArguments) {
        var command = this.$injector.resolveCommand(commandName);
        this.$options.validateOptions(command ? command.dashedOptions : null);
        Eif (!this.areDynamicSubcommandsRegistered) {
            this.$commandsServiceProvider.registerDynamicSubCommands();
            this.areDynamicSubcommandsRegistered = true;
        }
        return this.canExecuteCommand(commandName, commandArguments);
    };
    CommandsService.prototype.tryExecuteCommand = function (commandName, commandArguments) {
        var _this = this;
        return (function () {
            if (_this.executeCommandAction(commandName, commandArguments, _this.tryExecuteCommandAction).wait()) {
                _this.executeCommandAction(commandName, commandArguments, _this.executeCommandUnchecked).wait();
            }
            else {
                var command = _this.$injector.resolveCommand(commandName);
                Eif (command) {
                    _this.printHelp(commandName).wait();
                }
            }
        }).future()();
    };
    CommandsService.prototype.canExecuteCommand = function (commandName, commandArguments, isDynamicCommand) {
        var _this = this;
        return (function () {
            var command = _this.$injector.resolveCommand(commandName);
            var beautifiedName = helpers.stringReplaceAll(commandName, "|", " ");
            Eif (command) {
                Iif (command.isDisabled) {
                    _this.$errors.failWithoutHelp("This command is not applicable to your environment.");
                }
                Eif (command.canExecute) {
                    return command.canExecute(commandArguments).wait();
                }
                if (_this.$injector.isValidHierarchicalCommand(commandName, commandArguments)) {
                    return true;
                }
                if (_this.validateCommandArguments(command, commandArguments).wait()) {
                    return true;
                }
                _this.$errors.fail("Unable to execute command '%s'. Use '$ %s %s --help' for help.", beautifiedName, _this.$staticConfig.CLIENT_NAME.toLowerCase(), beautifiedName);
                return false;
            }
            else if (!isDynamicCommand && _.startsWith(commandName, _this.$commandsServiceProvider.dynamicCommandsPrefix)) {
                if (_.any(_this.$commandsServiceProvider.getDynamicCommands().wait())) {
                    _this.$commandsServiceProvider.generateDynamicCommands().wait();
                    return _this.canExecuteCommand(commandName, commandArguments, true).wait();
                }
            }
            _this.$logger.fatal("Unknown command '%s'. Use '%s help' for help.", beautifiedName, _this.$staticConfig.CLIENT_NAME.toLowerCase());
            _this.tryMatchCommand(commandName);
            return false;
        }).future()();
    };
    CommandsService.prototype.validateMandatoryParams = function (commandArguments, mandatoryParams) {
        var _this = this;
        return (function () {
            var commandArgsHelper = new CommandArgumentsValidationHelper(true, commandArguments);
            if (mandatoryParams.length > 0) {
                if (mandatoryParams.length > commandArguments.length) {
                    var customErrorMessages = _.map(mandatoryParams, function (mp) { return mp.errorMessage; });
                    customErrorMessages.splice(0, 0, "You need to provide all the required parameters.");
                    _this.$errors.fail(customErrorMessages.join(os_1.EOL));
                }
                _.each(mandatoryParams, function (mandatoryParam) {
                    var argument = _.find(commandArgsHelper.remainingArguments, function (c) { return mandatoryParam.validate(c).wait(); });
                    if (argument) {
                        helpers.remove(commandArgsHelper.remainingArguments, function (arg) { return arg === argument; });
                    }
                    else {
                        _this.$errors.fail("Missing mandatory parameter.");
                    }
                });
            }
            return commandArgsHelper;
        }).future()();
    };
    CommandsService.prototype.validateCommandArguments = function (command, commandArguments) {
        var _this = this;
        return (function () {
            var mandatoryParams = _.filter(command.allowedParameters, function (param) { return param.mandatory; });
            var commandArgsHelper = _this.validateMandatoryParams(commandArguments, mandatoryParams).wait();
            if (!commandArgsHelper.isValid) {
                return false;
            }
            if (!command.allowedParameters || command.allowedParameters.length === 0) {
                if (commandArguments.length > 0) {
                    _this.$errors.fail("This command doesn't accept parameters.");
                }
            }
            else {
                var unverifiedAllowedParams = command.allowedParameters.filter(function (param) { return !param.mandatory; });
                _.each(commandArgsHelper.remainingArguments, function (argument) {
                    var parameter = _.find(unverifiedAllowedParams, function (c) { return c.validate(argument).wait(); });
                    if (parameter) {
                        var index = unverifiedAllowedParams.indexOf(parameter);
                        unverifiedAllowedParams.splice(index, 1);
                    }
                    else {
                        _this.$errors.fail("The parameter %s is not valid for this command.", argument);
                    }
                });
            }
            return true;
        }).future()();
    };
    CommandsService.prototype.tryMatchCommand = function (commandName) {
        var _this = this;
        var allCommands = this.allCommands({ includeDevCommands: false });
        var similarCommands = [];
        _.each(allCommands, function (command) {
            if (!_this.$injector.isDefaultCommand(command)) {
                command = helpers.stringReplaceAll(command, "|", " ");
                var distance = jaroWinklerDistance(commandName, command);
                if (commandName.length > 3 && command.indexOf(commandName) !== -1) {
                    similarCommands.push({ rating: 1, name: command });
                }
                else if (distance >= 0.65) {
                    similarCommands.push({ rating: distance, name: command });
                }
            }
        });
        similarCommands = _.sortBy(similarCommands, function (command) {
            return -command.rating;
        }).slice(0, 5);
        if (similarCommands.length > 0) {
            var message = ["Did you mean?"];
            _.each(similarCommands, function (command) {
                message.push("\t" + command.name);
            });
            this.$logger.fatal(message.join("\n"));
        }
    };
    CommandsService.prototype.completeCommand = function () {
        var _this = this;
        return (function () {
            var tabtab = require("tabtab");
            var completeCallback = function (err, data) {
                if (err || !data) {
                    return;
                }
                var splittedLine = data.line.split(/[ ]+/);
                var line = _.filter(splittedLine, function (w) { return w !== ""; });
                var commandName = (line[line.length - 2]);
                var childrenCommands = _this.$injector.getChildrenCommandsNames(commandName);
                if (data.last && _.startsWith(data.last, "--")) {
                    return tabtab.log(_.keys(_this.$options.options), data, "--");
                }
                if (data.last && _.startsWith(data.last, "-")) {
                    return tabtab.log(_this.$options.shorthands, data, "-");
                }
                if (data.words === 1) {
                    var allCommands = _this.allCommands({ includeDevCommands: false });
                    if (_.startsWith(data.last, _this.$commandsServiceProvider.dynamicCommandsPrefix)) {
                        allCommands = allCommands.concat(_this.$commandsServiceProvider.getDynamicCommands().wait());
                    }
                    return tabtab.log(allCommands, data);
                }
                if (data.words >= 3) {
                    commandName = line[1] + "|" + line[2];
                }
                var command = _this.$injector.resolveCommand(commandName);
                if (command) {
                    var completionData = command.completionData;
                    if (completionData) {
                        return tabtab.log(completionData, data);
                    }
                }
                if (data.words === 2 && childrenCommands) {
                    return tabtab.log(_.reject(childrenCommands, function (children) { return children[0] === '*'; }), data);
                }
                return false;
            };
            tabtab.complete(_this.$staticConfig.CLIENT_NAME.toLowerCase(), completeCallback);
            if (_this.$staticConfig.CLIENT_NAME_ALIAS) {
                tabtab.complete(_this.$staticConfig.CLIENT_NAME_ALIAS.toLowerCase(), completeCallback);
            }
            return true;
        }).future()();
    };
    CommandsService.prototype.getCommandHelp = function () {
        var _this = this;
        return (function () {
            Iif (!_this.cachedCommandHelp && _this.$fs.exists(_this.$resources.resolvePath(_this.$staticConfig.COMMAND_HELP_FILE_NAME)).wait()) {
                _this.cachedCommandHelp = _this.$resources.readJson(_this.$staticConfig.COMMAND_HELP_FILE_NAME).wait();
            }
            return _this.cachedCommandHelp;
        }).future()();
    };
    CommandsService.prototype.beautifyCommandName = function (commandName) {
        Iif (commandName.indexOf("*") > 0) {
            return commandName.substr(0, commandName.indexOf("|"));
        }
        return commandName;
    };
    CommandsService.HIERARCHICAL_COMMANDS_DELIMITER = "|";
    CommandsService.HIERARCHICAL_COMMANDS_DEFAULT_COMMAND_DELIMITER = "|*";
    CommandsService.HOOKS_COMMANDS_DELIMITER = "-";
    return CommandsService;
})();
exports.CommandsService = CommandsService;
$injector.register("commandsService", CommandsService);