transit-im
Version:
express-like framework for AIM bots creation (ICQ as well)
136 lines (132 loc) • 3.83 kB
JavaScript
// Generated by CoffeeScript 1.6.3
(function() {
var _;
_ = require('underscore');
module.exports = {
parseCommand: function(command) {
var args, cmd, firstSpaceIdx, inQuotes, newArg, part, parts, _i, _len;
firstSpaceIdx = command.indexOf(' ');
args = [];
if (firstSpaceIdx > -1) {
cmd = command.substring(0, firstSpaceIdx).trim();
parts = command.substring(firstSpaceIdx).split(' ');
inQuotes = false;
newArg = '';
for (_i = 0, _len = parts.length; _i < _len; _i++) {
part = parts[_i];
if (part.trim().length === 0) {
continue;
}
if (part[0] === '"') {
inQuotes = true;
part = part.substring(1);
}
if (part[part.length - 1] === '"') {
inQuotes = false;
part = part.substring(0, part.length - 1);
}
if (newArg.length > 0) {
newArg += ' ';
}
newArg += part;
if (!inQuotes) {
args.push(newArg);
newArg = '';
}
}
} else {
cmd = command;
}
return {
cmd: cmd,
args: args
};
},
processArgs: function(commandPattern, argCallback) {
var args, cmd, _ref;
_ref = this.parseCommand(commandPattern), cmd = _ref.cmd, args = _ref.args;
return [cmd].concat(args.map(argCallback).map(function(a) {
if (a.indexOf(' ') >= 0) {
return '"' + a + '"';
} else {
return a;
}
})).join(" ");
},
parsePattern: function(pattern, cb) {
var parsed, part, parts, _i, _len;
if (cb == null) {
cb = function() {};
}
parts = pattern.split(' ');
parsed = {
cmd: parts.shift(),
args: [],
restArg: null,
match: function(cmd, args) {
if (cmd !== this.cmd) {
return null;
}
return this.collectArgs(args);
},
collectArgs: function(args) {
var arg, index, map, _i, _len;
map = {};
if (this.restArg) {
map[this.restArg] = [];
}
for (index = _i = 0, _len = args.length; _i < _len; index = ++_i) {
arg = args[index];
if (this.args[index]) {
map[this.args[index]] = arg;
} else if (this.restArg) {
map[this.restArg].push(arg);
}
}
return {
args: map,
cb: cb
};
}
};
for (_i = 0, _len = parts.length; _i < _len; _i++) {
part = parts[_i];
if (part[0] === '{') {
part = part.substring(1, part.length - 1);
}
if (part[0] === '{') {
parsed.restArg = part.substring(1, part.length - 1);
} else {
parsed.args.push(part);
}
}
return parsed;
},
forEachPortion: function(text, maxPortionLength, forPortion) {
var CRLF, buffer, index, length, lengths, lines, sum, _i, _len;
lines = text.split("\n");
lengths = lines.map(function(l) {
return l.length;
});
if (Math.max.apply(null, lengths) > maxPortionLength) {
throw "Cannot split text - there are lines larger than specified limit";
}
buffer = [];
sum = 0;
CRLF = 1;
for (index = _i = 0, _len = lengths.length; _i < _len; index = ++_i) {
length = lengths[index];
if (sum + length > maxPortionLength) {
forPortion(buffer.join("\n"));
buffer = [];
sum = 0;
}
buffer.push(lines[index]);
sum += length + CRLF;
}
if (buffer.length) {
return forPortion(buffer.join("\n"));
}
}
};
}).call(this);