code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
exports.getSanitizedExpressionForContent = function(babelTypes, blocks, keyPrefix) {
if (!blocks.length) {
return babelTypes.NullLiteral();
}
else if (blocks.length === 1) {
var firstBlock = blocks[0];
if (keyPrefix && firstBlock.openingElement) {
addKeyAttribute(babelTypes, firstBlock, keyPrefix);
}
return firstBlock;
}
for (var i = 0; i < blocks.length; i++) {
var thisBlock = blocks[i];
if (babelTypes.isJSXElement(thisBlock)) {
var key = keyPrefix ? keyPrefix + "-" + i : i;
addKeyAttribute(babelTypes, thisBlock, key);
}
}
return babelTypes.arrayExpression(blocks);
}; | Return either a NullLiteral (if no content is available) or
the single expression (if there is only one) or an ArrayExpression.
@param babelTypes - Babel lib
@param blocks - the content blocks
@param keyPrefix - a prefix to use when automatically generating keys
@returns {NullLiteral|Expression|ArrayExpression} | exports.getSanitizedExpressionForContent ( babelTypes , blocks , keyPrefix ) | javascript | AlexGilleran/jsx-control-statements | src/util/ast.js | https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js | MIT |
export const resolveTheme = async (mode, ipcRenderer) => {
let resolvedTheme = mode;
if (mode === Mode.SYSTEM) {
const nativeTheme = await ipcRenderer.invoke("get-native-theme");
resolvedTheme = nativeTheme.shouldUseDarkColors ? Theme.DARK : Theme.LIGHT;
}
return resolvedTheme;
}; | Determine the actual theme for system mode
@param {string} mode
@param {object} ipcRenderer
@returns {string} resolved theme | resolveTheme | javascript | ai-shifu/ChatALL | src/theme.js | https://github.com/ai-shifu/ChatALL/blob/master/src/theme.js | Apache-2.0 |
export const applyTheme = (theme, vuetifyTheme) => {
if (vuetifyTheme) {
vuetifyTheme.global.name.value = theme; // vuetify theme
}
}; | Apply theme to UI
@param {string} theme dark / light
@param {object} vuetifyTheme from veutify useTheme | applyTheme | javascript | ai-shifu/ChatALL | src/theme.js | https://github.com/ai-shifu/ChatALL/blob/master/src/theme.js | Apache-2.0 |
async _checkAvailability() {
return true;
} | Check whether the bot is logged in, settings are correct, etc.
@returns {boolean} - true if the bot is available, false otherwise. | _checkAvailability ( ) | javascript | ai-shifu/ChatALL | src/bots/PiBot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/PiBot.js | Apache-2.0 |
async createChatContext() {
return null;
} | Should implement this method if the bot supports conversation.
The conversation structure is defined by the subclass.
@param null
@returns {any} - Conversation structure. null if not supported. | createChatContext ( ) | javascript | ai-shifu/ChatALL | src/bots/PiBot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/PiBot.js | Apache-2.0 |
async _sendPrompt(prompt, onUpdateResponse, callbackParam) {
return new Promise((resolve, reject) => {
// Send the prompt to the bot and call onUpdateResponse() when the response is ready
// onUpdateResponse(callbackParam, {content, done})
// callbackParam: Just pass it to onUpdateResponse() as is
// Object.content: Response text from the bot, even if it's not fully complete
// Object.done: true if the response is completed, false otherwise
//
// When everything is done, call resolve()
// If there is an error, call reject(error)
try {
onUpdateResponse(callbackParam, {
content: "Hello, world!",
done: true,
});
resolve();
} catch (error) {
reject(error);
}
});
} | Send a prompt to the bot and call onResponse(response, callbackParam)
when the response is ready.
@param {string} prompt
@param {function} onUpdateResponse params: callbackParam, Object {content, done}
@param {object} callbackParam - Just pass it to onUpdateResponse() as is | _sendPrompt ( prompt , onUpdateResponse , callbackParam ) | javascript | ai-shifu/ChatALL | src/bots/TemplateBot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/TemplateBot.js | Apache-2.0 |
async createChatContext() {
let context = null;
const uuid = uuidv4();
try {
const createResponse = await axios.post(
`https://claude.ai/api/organizations/${store.state.claudeAi.org}/chat_conversations`,
{ name: "", uuid: uuid },
);
if (createResponse.status === 201) {
context = {
uuid,
};
} else {
console.error(
"Error ClaudeAI createChatContext status",
createResponse,
);
}
} catch (error) {
console.error("Error ClaudeAI createChatContext", error);
}
return context;
} | Should implement this method if the bot supports conversation.
The conversation structure is defined by the subclass.
@returns {any} - Conversation structure. null if not supported. | createChatContext ( ) | javascript | ai-shifu/ChatALL | src/bots/ClaudeAIBot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/ClaudeAIBot.js | Apache-2.0 |
async acquireLock(key, lockedFn, onLockUnavailable) {
const self = this;
return new Promise((resolve, reject) => {
(async () => {
await this.constructor._lock.acquire(
key,
async () => {
try {
const ret = await lockedFn();
resolve(ret);
} catch (err) {
reject(err);
}
},
async function (err, ret) {
if (err) {
// The lock is not available
onLockUnavailable();
try {
const ret = await self.constructor._lock.acquire(key, lockedFn); // Wait forever
resolve(ret);
} catch (err) {
reject(err);
}
} else {
resolve(ret);
}
},
{ timeout: 1 }, // Wait for only 1ms. Don't use 0 here.
);
})();
});
} | Acquire a lock for the given key and call lockedFn() when the lock is acquired.
If the lock is not available, call onLockUnavailable() and then try to acquire
the lock again.
@param {string} key
@param {function} lockedFn
@param {function} onLockUnavailable | acquireLock ( key , lockedFn , onLockUnavailable ) | javascript | ai-shifu/ChatALL | src/bots/Bot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/Bot.js | Apache-2.0 |
async _sendPrompt(prompt, onUpdateResponse, callbackParam) {
throw new Error(i18n.global.t("bot.notImplemented"));
} | Subclass should implement this method, not sendPrompt().
Send a prompt to the bot and call onResponse(response, callbackParam)
when the response is ready.
@param {string} prompt
@param {function} onUpdateResponse params: callbackParam, Object {content, done}
@param {object} callbackParam - Just pass it to onUpdateResponse() as is | _sendPrompt ( prompt , onUpdateResponse , callbackParam ) | javascript | ai-shifu/ChatALL | src/bots/Bot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/Bot.js | Apache-2.0 |
async _checkAvailability() {
return false;
} | Subclass must implement this method.
Check if the bot is logged in, settings are correct, etc.
@returns {boolean} - true if the bot is available, false otherwise. | _checkAvailability ( ) | javascript | ai-shifu/ChatALL | src/bots/Bot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/Bot.js | Apache-2.0 |
async getChatContext(createIfNotExists = true) {
let context = (await Chats.getCurrentChat())?.contexts?.[
this.getClassname()
];
if (!context && createIfNotExists) {
context = await this.createChatContext();
this.setChatContext(context);
}
return context;
} | Get the context from the store. If not available, create a new one.
@param {boolean} createIfNotExists - Create a new context if not exists
@returns {object} - Chat context defined by the bot | getChatContext ( createIfNotExists = true ) | javascript | ai-shifu/ChatALL | src/bots/Bot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/Bot.js | Apache-2.0 |
setRefreshCycle(cycle) {
const sr = this.constructor._sessionRefreshing;
sr.interval = cycle * 1000;
this.toggleSessionRefreshing(sr.interval > 0);
} | @param {int} cycle - Refresh cycle in seconds | setRefreshCycle ( cycle ) | javascript | ai-shifu/ChatALL | src/bots/openai/ChatGPTBot.js | https://github.com/ai-shifu/ChatALL/blob/master/src/bots/openai/ChatGPTBot.js | Apache-2.0 |
constructor(store, table, queueName = "") {
this.table = table;
this.store = store;
this.queueName = queueName;
} | @param {Store} store
@param {Table} table
@param {string} queueName | constructor ( store , table , queueName = "" ) | javascript | ai-shifu/ChatALL | src/store/queue.js | https://github.com/ai-shifu/ChatALL/blob/master/src/store/queue.js | Apache-2.0 |
function getNumberCodeRanges(numType) {
if (numType === 'x' || numType === 'X') {
this.index += 2;
return [
[48, 57], // 0-9
[65, 70], // A-F
[97, 102], // a-f
];
}
else if (numType === 'b' || numType === 'B') {
this.index += 2;
return [[48, 49]]; // 0-1
}
else if (numType === 'o' || numType === 'O' ||
(numType >= '0' && numType <= '7')) { // 0-7 allows non-standard 0644 = 420
this.index += numType <= '7' ? 1 : 2;
return [[48, 55]]; // 0-7
}
return null;
} | Gets the range of allowable number codes (decimal) and updates index
@param {string} numType
@returns {number[][]|null} | getNumberCodeRanges ( numType ) | javascript | EricSmekens/jsep | packages/numbers/src/index.js | https://github.com/EricSmekens/jsep/blob/master/packages/numbers/src/index.js | MIT |
function getNumberBase(numType) {
if (numType === 'x' || numType === 'X') {
return 16;
}
else if (numType === 'b' || numType === 'B') {
return 2;
}
// default (includes non-stand 044)
return 8;
} | Supports Hex, Octal and Binary only
@param {string} numType
@returns {16|8|2} | getNumberBase ( numType ) | javascript | EricSmekens/jsep | packages/numbers/src/index.js | https://github.com/EricSmekens/jsep/blob/master/packages/numbers/src/index.js | MIT |
function isUnderscoreOrWithinRange(code, ranges) {
return code === UNDERSCORE ||
ranges.some(([min, max]) => code >= min && code <= max);
} | Verifies number code is within given ranges
@param {number} code
@param {number[][]} ranges | isUnderscoreOrWithinRange ( code , ranges ) | javascript | EricSmekens/jsep | packages/numbers/src/index.js | https://github.com/EricSmekens/jsep/blob/master/packages/numbers/src/index.js | MIT |
register(...plugins) {
plugins.forEach((plugin) => {
if (typeof plugin !== 'object' || !plugin.name || !plugin.init) {
throw new Error('Invalid JSEP plugin format');
}
if (this.registered[plugin.name]) {
// already registered. Ignore.
return;
}
plugin.init(this.jsep);
this.registered[plugin.name] = plugin;
});
} | Adds the given plugin(s) to the registry
@param {object} plugins
@param {string} plugins.name The name of the plugin
@param {PluginSetup} plugins.init The init function
@public | register ( ... plugins ) | javascript | EricSmekens/jsep | src/plugins.js | https://github.com/EricSmekens/jsep/blob/master/src/plugins.js | MIT |
static addUnaryOp(op_name) {
Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
Jsep.unary_ops[op_name] = 1;
return Jsep;
} | @method addUnaryOp
@param {string} op_name The name of the unary op to add
@returns {Jsep} | addUnaryOp ( op_name ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static addBinaryOp(op_name, precedence, isRightAssociative) {
Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
Jsep.binary_ops[op_name] = precedence;
if (isRightAssociative) {
Jsep.right_associative.add(op_name);
}
else {
Jsep.right_associative.delete(op_name);
}
return Jsep;
} | @method jsep.addBinaryOp
@param {string} op_name The name of the binary op to add
@param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
@param {boolean} [isRightAssociative=false] whether operator is right-associative
@returns {Jsep} | addBinaryOp ( op_name , precedence , isRightAssociative ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static addIdentifierChar(char) {
Jsep.additional_identifier_chars.add(char);
return Jsep;
} | @method addIdentifierChar
@param {string} char The additional character to treat as a valid part of an identifier
@returns {Jsep} | addIdentifierChar ( char ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static addLiteral(literal_name, literal_value) {
Jsep.literals[literal_name] = literal_value;
return Jsep;
} | @method addLiteral
@param {string} literal_name The name of the literal to add
@param {*} literal_value The value of the literal
@returns {Jsep} | addLiteral ( literal_name , literal_value ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeUnaryOp(op_name) {
delete Jsep.unary_ops[op_name];
if (op_name.length === Jsep.max_unop_len) {
Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
}
return Jsep;
} | @method removeUnaryOp
@param {string} op_name The name of the unary op to remove
@returns {Jsep} | removeUnaryOp ( op_name ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeAllUnaryOps() {
Jsep.unary_ops = {};
Jsep.max_unop_len = 0;
return Jsep;
} | @method removeAllUnaryOps
@returns {Jsep} | removeAllUnaryOps ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeIdentifierChar(char) {
Jsep.additional_identifier_chars.delete(char);
return Jsep;
} | @method removeIdentifierChar
@param {string} char The additional character to stop treating as a valid part of an identifier
@returns {Jsep} | removeIdentifierChar ( char ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeBinaryOp(op_name) {
delete Jsep.binary_ops[op_name];
if (op_name.length === Jsep.max_binop_len) {
Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
}
Jsep.right_associative.delete(op_name);
return Jsep;
} | @method removeBinaryOp
@param {string} op_name The name of the binary op to remove
@returns {Jsep} | removeBinaryOp ( op_name ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeAllBinaryOps() {
Jsep.binary_ops = {};
Jsep.max_binop_len = 0;
return Jsep;
} | @method removeAllBinaryOps
@returns {Jsep} | removeAllBinaryOps ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeLiteral(literal_name) {
delete Jsep.literals[literal_name];
return Jsep;
} | @method removeLiteral
@param {string} literal_name The name of the literal to remove
@returns {Jsep} | removeLiteral ( literal_name ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static removeAllLiterals() {
Jsep.literals = {};
return Jsep;
} | @method removeAllLiterals
@returns {Jsep} | removeAllLiterals ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
constructor(expr) {
// `index` stores the character number we are currently at
// All of the gobbles below will modify `index` as we move along
this.expr = expr;
this.index = 0;
} | @param {string} expr a string with the passed in express
@returns Jsep | constructor ( expr ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static parse(expr) {
return (new Jsep(expr)).parse();
} | static top-level parser
@returns {jsep.Expression} | parse ( expr ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static getMaxKeyLen(obj) {
return Math.max(0, ...Object.keys(obj).map(k => k.length));
} | Get the longest key length of any object
@param {object} obj
@returns {number} | getMaxKeyLen ( obj ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0...9
} | `ch` is a character code in the next three functions
@param {number} ch
@returns {boolean} | isDecimalDigit ( ch ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static binaryPrecedence(op_val) {
return Jsep.binary_ops[op_val] || 0;
} | Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
@param {string} op_val
@returns {number} | binaryPrecedence ( op_val ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static isIdentifierStart(ch) {
return (ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)]) || // any non-ASCII that is not an operator
(Jsep.additional_identifier_chars.has(String.fromCharCode(ch))); // additional characters
} | Looks for start of identifier
@param {number} ch
@returns {boolean} | isIdentifierStart ( ch ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
static isIdentifierPart(ch) {
return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
} | @param {number} ch
@returns {boolean} | isIdentifierPart ( ch ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
throwError(message) {
const error = new Error(message + ' at character ' + this.index);
error.index = this.index;
error.description = message;
throw error;
} | throw error at index of the expression
@param {string} message
@throws | throwError ( message ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
runHook(name, node) {
if (Jsep.hooks[name]) {
const env = { context: this, node };
Jsep.hooks.run(name, env);
return env.node;
}
return node;
} | Run a given hook
@param {string} name
@param {jsep.Expression|false} [node]
@returns {?jsep.Expression} | runHook ( name , node ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
searchHook(name) {
if (Jsep.hooks[name]) {
const env = { context: this };
Jsep.hooks[name].find(function (callback) {
callback.call(env.context, env);
return env.node;
});
return env.node;
}
} | Runs a given hook until one returns a node
@param {string} name
@returns {?jsep.Expression} | searchHook ( name ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleSpaces() {
let ch = this.code;
// Whitespace
while (ch === Jsep.SPACE_CODE
|| ch === Jsep.TAB_CODE
|| ch === Jsep.LF_CODE
|| ch === Jsep.CR_CODE) {
ch = this.expr.charCodeAt(++this.index);
}
this.runHook('gobble-spaces');
} | Push `index` up to the next non-space character | gobbleSpaces ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
parse() {
this.runHook('before-all');
const nodes = this.gobbleExpressions();
// If there's only one expression just try returning the expression
const node = nodes.length === 1
? nodes[0]
: {
type: Jsep.COMPOUND,
body: nodes
};
return this.runHook('after-all', node);
} | Top-level method to parse all expressions and returns compound or single node
@returns {jsep.Expression} | parse ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleExpressions(untilICode) {
let nodes = [], ch_i, node;
while (this.index < this.expr.length) {
ch_i = this.code;
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
this.index++; // ignore separators
}
else {
// Try to gobble each expression individually
if (node = this.gobbleExpression()) {
nodes.push(node);
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
}
else if (this.index < this.expr.length) {
if (ch_i === untilICode) {
break;
}
this.throwError('Unexpected "' + this.char + '"');
}
}
}
return nodes;
} | top-level parser (but can be reused within as well)
@param {number} [untilICode]
@returns {jsep.Expression[]} | gobbleExpressions ( untilICode ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleExpression() {
const node = this.searchHook('gobble-expression') || this.gobbleBinaryExpression();
this.gobbleSpaces();
return this.runHook('after-expression', node);
} | The main parsing function.
@returns {?jsep.Expression} | gobbleExpression ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleBinaryOp() {
this.gobbleSpaces();
let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
let tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept a binary op when it is an identifier.
// Binary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (Jsep.binary_ops.hasOwnProperty(to_check) && (
!Jsep.isIdentifierStart(this.code) ||
(this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))
)) {
this.index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
} | Search for the operation portion of the string (e.g. `+`, `===`)
Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
and move down from 3 to 2 to 1 character until a matching binary operation is found
then, return that binary operation
@returns {string|boolean} | gobbleBinaryOp ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleToken() {
let ch, to_check, tc_len, node;
this.gobbleSpaces();
node = this.searchHook('gobble-token');
if (node) {
return this.runHook('after-token', node);
}
ch = this.code;
if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return this.gobbleNumericLiteral();
}
if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
// Single or double quotes
node = this.gobbleStringLiteral();
}
else if (ch === Jsep.OBRACK_CODE) {
node = this.gobbleArray();
}
else {
to_check = this.expr.substr(this.index, Jsep.max_unop_len);
tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept an unary op when it is an identifier.
// Unary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (Jsep.unary_ops.hasOwnProperty(to_check) && (
!Jsep.isIdentifierStart(this.code) ||
(this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))
)) {
this.index += tc_len;
const argument = this.gobbleToken();
if (!argument) {
this.throwError('missing unaryOp argument');
}
return this.runHook('after-token', {
type: Jsep.UNARY_EXP,
operator: to_check,
argument,
prefix: true
});
}
to_check = to_check.substr(0, --tc_len);
}
if (Jsep.isIdentifierStart(ch)) {
node = this.gobbleIdentifier();
if (Jsep.literals.hasOwnProperty(node.name)) {
node = {
type: Jsep.LITERAL,
value: Jsep.literals[node.name],
raw: node.name,
};
}
else if (node.name === Jsep.this_str) {
node = { type: Jsep.THIS_EXP };
}
}
else if (ch === Jsep.OPAREN_CODE) { // open parenthesis
node = this.gobbleGroup();
}
}
if (!node) {
return this.runHook('after-token', false);
}
node = this.gobbleTokenProperty(node);
return this.runHook('after-token', node);
} | An individual part of a binary expression:
e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
@returns {boolean|jsep.Expression} | gobbleToken ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleArguments(termination) {
const args = [];
let closed = false;
let separator_count = 0;
while (this.index < this.expr.length) {
this.gobbleSpaces();
let ch_i = this.code;
if (ch_i === termination) { // done parsing
closed = true;
this.index++;
if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length){
this.throwError('Unexpected token ' + String.fromCharCode(termination));
}
break;
}
else if (ch_i === Jsep.COMMA_CODE) { // between expressions
this.index++;
separator_count++;
if (separator_count !== args.length) { // missing argument
if (termination === Jsep.CPAREN_CODE) {
this.throwError('Unexpected token ,');
}
else if (termination === Jsep.CBRACK_CODE) {
for (let arg = args.length; arg < separator_count; arg++) {
args.push(null);
}
}
}
}
else if (args.length !== separator_count && separator_count !== 0) {
// NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments
this.throwError('Expected comma');
}
else {
const node = this.gobbleExpression();
if (!node || node.type === Jsep.COMPOUND) {
this.throwError('Expected comma');
}
args.push(node);
}
}
if (!closed) {
this.throwError('Expected ' + String.fromCharCode(termination));
}
return args;
} | Gobbles a list of arguments within the context of a function call
or array literal. This function also assumes that the opening character
`(` or `[` has already been gobbled, and gobbles expressions and commas
until the terminator character `)` or `]` is encountered.
e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
@param {number} termination
@returns {jsep.Expression[]} | gobbleArguments ( termination ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
gobbleGroup() {
this.index++;
let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
if (this.code === Jsep.CPAREN_CODE) {
this.index++;
if (nodes.length === 1) {
return nodes[0];
}
else if (!nodes.length) {
return false;
}
else {
return {
type: Jsep.SEQUENCE_EXP,
expressions: nodes,
};
}
}
else {
this.throwError('Unclosed (');
}
} | Responsible for parsing a group of things within parentheses `()`
that have no identifier in front (so not a function call)
This function assumes that it needs to gobble the opening parenthesis
and then tries to gobble everything within that parenthesis, assuming
that the next thing it should see is the close parenthesis. If not,
then the expression probably doesn't have a `)`
@returns {boolean|jsep.Expression} | gobbleGroup ( ) | javascript | EricSmekens/jsep | src/jsep.js | https://github.com/EricSmekens/jsep/blob/master/src/jsep.js | MIT |
add(name, callback, first) {
if (typeof arguments[0] != 'string') {
// Multiple hook callbacks, keyed by name
for (let name in arguments[0]) {
this.add(name, arguments[0][name], arguments[1]);
}
}
else {
(Array.isArray(name) ? name : [name]).forEach(function (name) {
this[name] = this[name] || [];
if (callback) {
this[name][first ? 'unshift' : 'push'](callback);
}
}, this);
}
}
/**
* Runs a hook invoking all registered callbacks with the given environment variables.
*
* Callbacks will be invoked synchronously and in the order in which they were registered.
*
* @param {string} name The name of the hook.
* @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
* @public
*/
run(name, env) {
this[name] = this[name] || [];
this[name].forEach(function (callback) {
callback.call(env && env.context ? env.context : env, env);
});
}
} | Adds the given callback to the list of callbacks for the given hook.
The callback will be invoked when the hook it is registered for is run.
One callback function can be registered to multiple hooks and the same hook multiple times.
@param {string|object} name The name of the hook, or an object of callbacks keyed by name
@param {HookCallback|boolean} callback The callback function which is given environment variables.
@param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
@public | add ( name , callback , first ) | javascript | EricSmekens/jsep | src/hooks.js | https://github.com/EricSmekens/jsep/blob/master/src/hooks.js | MIT |
exports.print = function() {
exports.stdout.print.apply(exports.stdout, arguments);
}; | A utility function to write to stdout. | exports.print ( ) | javascript | ringo/ringojs | modules/system.js | https://github.com/ringo/ringojs/blob/master/modules/system.js | Apache-2.0 |
exports.exit = function(status) {
System.exit(status || 0);
}; | Terminates the current process.
@param {Number} status The exit status, defaults to 0. | exports.exit ( status ) | javascript | ringo/ringojs | modules/system.js | https://github.com/ringo/ringojs/blob/master/modules/system.js | Apache-2.0 |
const run = exports.run = function(scope, name, writer) {
if (arguments.length === 2) {
if (typeof(arguments[1]) === "object") {
writer = name;
name = undefined;
} else {
writer = new TermWriter();
}
} else if (arguments.length === 1) {
writer = new TermWriter();
}
if (typeof(scope) === "string") {
scope = require(fs.resolve(fs.workingDirectory(), scope));
}
const summary = {
"testsRun": 0,
"passed": 0,
"errors": 0,
"failures": 0,
"time": 0
};
writer.writeHeader();
if (name !== undefined) {
executeTest(scope, name, summary, writer, []);
} else {
executeTestScope(scope, summary, writer, []);
}
scope = null;
writer.writeSummary(summary);
return summary.failures + summary.errors;
}; | The main runner method. This method can be called with one, two or three
arguments: <code>run(scope)</code>, <code>run(scope, nameOfTest)</code>,
<code>run(scope, writer)</code> or <code>run(scope, nameOfTest, writer)</code>
@param {String|Object} scope Either the path to a module containing unit
tests to execute, or an object containing the exported test methods or nested scopes.
@param {String} name Optional name of a test method to execute
@param {Object} writer Optional writer to use for displaying the test results. Defaults
to TermWriter. | exports.run ( scope , name , writer ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
const executeTestScope = (scope, summary, writer, path) => {
// loop over all exported properties and see if there are test methods to run
Object.keys(scope).forEach(name => {
if (name !== "test" && strings.startsWith(name, "test")) {
executeTest(scope, name, summary, writer, path);
}
});
}; | Loops over all properties of a test scope and executes all methods whose
name starts with "test".
@param {Object} scope The scope object containing the test functions
@param {Object} summary An object containing summary information
@param {Object} writer A writer instance for displaying test results
@param {Array} path An array containing property path segments | executeTestScope | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
const executeTest = (scope, name, summary, writer, path) => {
const value = scope[name];
if (value instanceof Function) {
writer.writeTestStart(name);
let start = null;
let time = 0;
try {
// execute setUp, if defined
if (typeof(scope.setUp) === "function") {
scope.setUp();
}
// execute test function
start = Date.now();
value();
time = Date.now() - start;
writer.writeTestPassed(time);
summary.passed += 1;
} catch (e) {
if (!(e instanceof AssertionError) && !(e instanceof ArgumentsError)) {
e = new EvaluationError(e);
}
writer.writeTestFailed(e);
if (e instanceof AssertionError) {
summary.failures += 1;
} else {
summary.errors += 1;
}
} finally {
// execute tearDown, if defined
if (typeof(scope.tearDown) === "function") {
scope.tearDown();
}
summary.testsRun += 1;
summary.time += time;
}
} else if (value.constructor === Object) {
writer.enterScope(name);
executeTestScope(value, summary, writer, path.concat([name]));
writer.exitScope(name);
}
}; | Executes a single test, which can be either a single test method
or a test submodule.
@param {Object} scope The scope object containing the test
@param {String} name The name of the test to execute
@param {Object} summary An object containing summary information
@param {Object} writer A writer instance for displaying test results
@param {Array} path An array containing property path segments | executeTest | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
const TermWriter = function() {
this.indent = "";
return this;
}; | Constructs a new TermWriter instance
@class Instances of this class represent a writer for displaying test results
in the shell
@returns {TermWriter} A newly created TermWriter instance
@constructor | TermWriter ( ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.writeHeader = function() {
term.writeln("================================================================================");
return;
}; | Write a header at the beginning of a unit test(suite) | TermWriter.prototype.writeHeader ( ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.enterScope = function(name) {
term.writeln(this.indent, "+ Running", name, "...");
this.indent += " ";
}; | Notification that we're entering a new test scope.
@param {String} name the name of the test scope | TermWriter.prototype.enterScope ( name ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.exitScope = function() {
this.indent = this.indent.substring(2);
}; | Notification that we're leaving a test scope. | TermWriter.prototype.exitScope ( ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.writeTestStart = function(name) {
term.write(this.indent, "+ Running", name, "...");
}; | Display the beginning of a test function execution
@param {String} name The name of the test function about to be executed | TermWriter.prototype.writeTestStart ( name ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.writeTestPassed = function(time) {
term.writeln(term.BOLD, " PASSED", term.RESET, "(" + time + " ms)");
}; | Display a passed test method execution
@param {Number} time The time the execution of the test method took | TermWriter.prototype.writeTestPassed ( time ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.writeSummary = function(summary) {
if (summary.testsRun > 0) {
term.writeln("--------------------------------------------------------------------------------");
term.writeln("Executed", summary.testsRun, "tests in", summary.time, "ms ");
term.writeln(term.BOLD, "Passed", summary.passed + ";", "Failed", summary.failures + ";", "Errors", summary.errors + ";");
} else {
term.writeln("No tests found");
}
}; | Display the summary of a unit test(suite) execution
@param {Object} summary The unit test summary | TermWriter.prototype.writeSummary ( summary ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
const EvaluationError = function(messageOrException) {
let message = undefined;
let exception = null;
let stackTrace = null;
let fileName = null;
let lineNumber = -1;
if (messageOrException instanceof Error) {
exception = messageOrException;
} else if (typeof(messageOrException.toString) === 'function') {
message = messageOrException.toString();
} else {
message = messageOrException;
}
if (exception != null) {
if (exception.rhinoException != null) {
const e = exception.rhinoException;
message += e.details();
stackTrace = getStackTrace(e.getStackTrace());
} else if (exception instanceof Error) {
message = exception.message;
}
if (!stackTrace) {
// got no stack trace, so add at least filename and line number
fileName = exception.fileName || null;
lineNumber = exception.lineNumber || null;
}
}
Object.defineProperties(this, {
"message": {
"value": message
},
"stackTrace": {
"value": stackTrace
},
"fileName": {
"value": fileName
},
"lineNumber": {
"value": lineNumber
}
});
return this;
}; | Creates a new EvaluationError instance
@class Instances of this class represent an exception thrown when evaluating
a test file or a single test function
@param {Object} messageOrException Either a message string or the exception
thrown when evaluating
@returns A newly created EvaluationError instance
@constructor
@exteds TestException | EvaluationError ( messageOrException ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
TermWriter.prototype.writeTestFailed = function(exception) {
term.writeln(term.BOLD, term.WHITE, term.ONRED, " FAILED ");
exception.message.split(/\n/).forEach(function(line) {
term.writeln(" ", term.BOLD, term.RED, line);
});
if (exception.stackTrace != null) {
exception.stackTrace.forEach(function(line) {
term.writeln(" ", term.BOLD, line);
});
} else if (exception.fileName) {
term.writeln(" at " + exception.fileName + ":" + exception.lineNumber);
}
term.writeln("");
};
/**
* Display the summary of a unit test(suite) execution
* @param {Object} summary The unit test summary
*/
TermWriter.prototype.writeSummary = function(summary) {
if (summary.testsRun > 0) {
term.writeln("--------------------------------------------------------------------------------");
term.writeln("Executed", summary.testsRun, "tests in", summary.time, "ms ");
term.writeln(term.BOLD, "Passed", summary.passed + ";", "Failed", summary.failures + ";", "Errors", summary.errors + ";");
} else {
term.writeln("No tests found");
}
};
/**
* Creates a new EvaluationError instance
* @class Instances of this class represent an exception thrown when evaluating
* a test file or a single test function
* @param {Object} messageOrException Either a message string or the exception
* thrown when evaluating
* @returns A newly created EvaluationError instance
* @constructor
* @exteds TestException
*/
const EvaluationError = function(messageOrException) {
let message = undefined;
let exception = null;
let stackTrace = null;
let fileName = null;
let lineNumber = -1;
if (messageOrException instanceof Error) {
exception = messageOrException;
} else if (typeof(messageOrException.toString) === 'function') {
message = messageOrException.toString();
} else {
message = messageOrException;
}
if (exception != null) {
if (exception.rhinoException != null) {
const e = exception.rhinoException;
message += e.details();
stackTrace = getStackTrace(e.getStackTrace());
} else if (exception instanceof Error) {
message = exception.message;
}
if (!stackTrace) {
// got no stack trace, so add at least filename and line number
fileName = exception.fileName || null;
lineNumber = exception.lineNumber || null;
}
}
Object.defineProperties(this, {
"message": {
"value": message
},
"stackTrace": {
"value": stackTrace
},
"fileName": {
"value": fileName
},
"lineNumber": {
"value": lineNumber
}
});
return this;
};
EvaluationError.prototype = Object.create(Error.prototype);
EvaluationError.prototype.constructor = EvaluationError;
/**
* Executed when called from the command line
*/
if (require.main === module) {
const system = require("system");
if (system.args.length === 1) {
term.writeln("Usage: bin/ringo test test/file1 test/file2");
} else {
const writer = new TermWriter();
const failures = system.args.slice(1).reduce((result, arg) => {
return result + this.run(arg, writer);
}, 0);
system.exit(failures);
}
} | Display a failed test
@param {Object} exception The exception thrown during test method execution | TermWriter.prototype.writeTestFailed ( exception ) | javascript | ringo/ringojs | modules/test.js | https://github.com/ringo/ringojs/blob/master/modules/test.js | Apache-2.0 |
Stream.prototype.copy = function(output) {
const length = 8192;
const buffer = new binary.ByteArray(length);
let read = -1;
while ((read = this.readInto(buffer, 0, length)) > -1) {
output.write(buffer, 0, read);
}
output.flush();
return this;
}; | Reads all data available from this stream and writes the result to the
given output stream, flushing afterwards. Note that this function does
not close this stream or the output stream after copying.
@param {Stream} output The target Stream to be written to. | Stream.prototype.copy ( output ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
Stream.prototype.forEach = function(fn, thisObj) {
const length = 8192;
const buffer = new binary.ByteArray(length);
let read = -1;
while ((read = this.readInto(buffer, 0, length)) > -1) {
buffer.length = read;
fn.call(thisObj, buffer);
buffer.length = length;
}
}; | Read all data from this stream and invoke function `fn` for each chunk of data read.
The callback function is called with a ByteArray as single argument. Note that
the stream is not closed after reading.
@param {Function} fn the callback function
@param {Object} [thisObj] optional this-object to use for callback | Stream.prototype.forEach ( fn , thisObj ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.readable = function() {
return true;
}; | Returns true if the stream supports reading, false otherwise.
Always returns true for MemoryStreams.
@name MemoryStream.prototype.readable
@see #Stream.prototype.readable
@return {Boolean} true if stream is readable
@function | stream.readable ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.writable = function() {
return buffer instanceof binary.ByteArray;
}; | Returns true if the stream supports writing, false otherwise.
For MemoryStreams this returns true if the wrapped binary is an
instance of ByteArray.
@name MemoryStream.prototype.writable
@see #Stream.prototype.writable
@return {Boolean} true if stream is writable
@function | stream.writable ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.seekable = function() {
return true;
}; | Returns true if the stream is randomly accessible and supports the length
and position properties, false otherwise.
Always returns true for MemoryStreams.
@name MemoryStream.prototype.seekable
@see #Stream.prototype.seekable
@return {Boolean} true if stream is seekable
@function | stream.seekable ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.read = function(maxBytes) {
checkClosed();
let result;
if (isFinite(maxBytes)) {
if (maxBytes < 0) {
throw new Error("read(): argument must not be negative");
}
const end = Math.min(position + maxBytes, length);
result = binary.ByteString.wrap(buffer.slice(position, end));
position = end;
return result;
} else {
result = binary.ByteString.wrap(buffer.slice(position, length));
position = length;
}
return result;
}; | Read up to `maxBytes` bytes from the stream, or until the end of the stream
has been reached. If `maxBytes` is not specified, the full stream is read
until its end is reached. Reading from a stream where the end has already been
reached returns an empty ByteString.
@name MemoryStream.prototype.read
@param {Number} maxBytes the maximum number of bytes to read
@returns {ByteString}
@see #Stream.prototype.read
@function | stream.read ( maxBytes ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.readInto = function(target, begin, end) {
checkClosed();
if (!(target instanceof binary.ByteArray)) {
throw new Error("readInto(): first argument must be ByteArray");
}
if (position >= length) {
return -1;
}
begin = begin === undefined ? 0 : Math.max(0, begin);
end = end === undefined ? target.length : Math.min(target.length, end);
if (begin < 0 || end < 0) {
throw new Error("readInto(): begin and end must not be negative");
} else if (begin > end) {
throw new Error("readInto(): end must be greater than begin");
}
const count = Math.min(length - position, end - begin);
buffer.copy(position, position + count, target, begin);
position += count;
return count;
}; | Read bytes from this stream into the given buffer. This method does
*not* increase the length of the buffer.
@name MemoryStream.prototype.readInto
@param {ByteArray} buffer the buffer
@param {Number} begin optional begin index, defaults to 0.
@param {Number} end optional end index, defaults to buffer.length - 1.
@returns {Number} The number of bytes read or -1 if the end of the stream
has been reached
@see #Stream.prototype.readInto
@function | stream.readInto ( target , begin , end ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.write = function(source, begin, end) {
checkClosed();
if (typeof source === "string") {
require("system").stderr.print("Warning: binary write called with string argument. "
+ "Using default encoding");
source = binary.toByteString(source);
}
if (!(source instanceof binary.Binary)) {
throw new Error("write(): first argument must be binary");
}
begin = begin === undefined ? 0 : Math.max(0, begin);
end = end === undefined ? source.length : Math.min(source.length, end);
if (begin > end) {
throw new Error("write(): end must be greater than begin");
}
const count = end - begin;
source.copy(begin, end, buffer, position);
position += count;
length = Math.max(length, position);
}; | Write bytes from b to this stream. If begin and end are specified,
only the range starting at begin and ending before end is written.
@name MemoryStream.prototype.write
@param {Binary} source The source to be written from
@param {Number} begin optional
@param {Number} end optional
@see #Stream.prototype.write
@function | stream.write ( source , begin , end ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.skip = function(num) {
checkClosed();
num = Math.min(parseInt(num, 10), length - position);
if (isNaN(num)) {
throw new Error("skip() requires a number argument");
} else if (num < 0) {
throw new Error("Argument to skip() must not be negative");
}
position += num;
return num
}; | Try to skip over num bytes in the stream. Returns the number of acutal bytes skipped
or throws an error if the operation could not be completed.
@name Stream.prototype.skip
@param {Number} num bytes to skip
@returns {Number} actual bytes skipped
@name MemoryStream.prototype.skip
@function | stream.skip ( num ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.flush = function() {
checkClosed();
}; | Flushes the bytes written to the stream to the underlying medium.
@name MemoryStream.prototype.flush
@function | stream.flush ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.close = function() {
checkClosed();
closed = true;
}; | Closes the stream, freeing the resources it is holding.
@name MemoryStream.prototype.close
@function | stream.close ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
stream.closed = function() {
return closed;
}; | Returns true if the stream is closed, false otherwise.
@name MemoryStream.prototype.closed
@return {Boolean} true if the stream has been closed
@function | stream.closed ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
exports.MemoryStream = function MemoryStream(binaryOrNumber) {
let buffer, length;
if (!binaryOrNumber) {
buffer = new binary.ByteArray(0);
length = 0;
} else if (binaryOrNumber instanceof binary.Binary) {
buffer = binaryOrNumber;
length = buffer.length;
} else if (typeof binaryOrNumber == "number") {
buffer = new binary.ByteArray(binaryOrNumber);
length = 0;
} else {
throw new Error("Argument must be Binary, Number, or undefined");
}
const stream = Object.create(Stream.prototype);
const canWrite = buffer instanceof binary.ByteArray;
let position = 0;
let closed = false;
function checkClosed() {
if (closed) {
throw new Error("Stream has been closed");
}
}
/**
* Returns true if the stream supports reading, false otherwise.
* Always returns true for MemoryStreams.
* @name MemoryStream.prototype.readable
* @see #Stream.prototype.readable
* @return {Boolean} true if stream is readable
* @function
*/
stream.readable = function() {
return true;
};
/**
* Returns true if the stream supports writing, false otherwise.
* For MemoryStreams this returns true if the wrapped binary is an
* instance of ByteArray.
* @name MemoryStream.prototype.writable
* @see #Stream.prototype.writable
* @return {Boolean} true if stream is writable
* @function
*/
stream.writable = function() {
return buffer instanceof binary.ByteArray;
};
/**
* Returns true if the stream is randomly accessible and supports the length
* and position properties, false otherwise.
* Always returns true for MemoryStreams.
* @name MemoryStream.prototype.seekable
* @see #Stream.prototype.seekable
* @return {Boolean} true if stream is seekable
* @function
*/
stream.seekable = function() {
return true;
};
/**
* Read up to `maxBytes` bytes from the stream, or until the end of the stream
* has been reached. If `maxBytes` is not specified, the full stream is read
* until its end is reached. Reading from a stream where the end has already been
* reached returns an empty ByteString.
* @name MemoryStream.prototype.read
* @param {Number} maxBytes the maximum number of bytes to read
* @returns {ByteString}
* @see #Stream.prototype.read
* @function
*/
stream.read = function(maxBytes) {
checkClosed();
let result;
if (isFinite(maxBytes)) {
if (maxBytes < 0) {
throw new Error("read(): argument must not be negative");
}
const end = Math.min(position + maxBytes, length);
result = binary.ByteString.wrap(buffer.slice(position, end));
position = end;
return result;
} else {
result = binary.ByteString.wrap(buffer.slice(position, length));
position = length;
}
return result;
};
/**
* Read bytes from this stream into the given buffer. This method does
* *not* increase the length of the buffer.
* @name MemoryStream.prototype.readInto
* @param {ByteArray} buffer the buffer
* @param {Number} begin optional begin index, defaults to 0.
* @param {Number} end optional end index, defaults to buffer.length - 1.
* @returns {Number} The number of bytes read or -1 if the end of the stream
* has been reached
* @see #Stream.prototype.readInto
* @function
*/
stream.readInto = function(target, begin, end) {
checkClosed();
if (!(target instanceof binary.ByteArray)) {
throw new Error("readInto(): first argument must be ByteArray");
}
if (position >= length) {
return -1;
}
begin = begin === undefined ? 0 : Math.max(0, begin);
end = end === undefined ? target.length : Math.min(target.length, end);
if (begin < 0 || end < 0) {
throw new Error("readInto(): begin and end must not be negative");
} else if (begin > end) {
throw new Error("readInto(): end must be greater than begin");
}
const count = Math.min(length - position, end - begin);
buffer.copy(position, position + count, target, begin);
position += count;
return count;
};
/**
* Write bytes from b to this stream. If begin and end are specified,
* only the range starting at begin and ending before end is written.
* @name MemoryStream.prototype.write
* @param {Binary} source The source to be written from
* @param {Number} begin optional
* @param {Number} end optional
* @see #Stream.prototype.write
* @function
*/
stream.write = function(source, begin, end) {
checkClosed();
if (typeof source === "string") {
require("system").stderr.print("Warning: binary write called with string argument. "
+ "Using default encoding");
source = binary.toByteString(source);
}
if (!(source instanceof binary.Binary)) {
throw new Error("write(): first argument must be binary");
}
begin = begin === undefined ? 0 : Math.max(0, begin);
end = end === undefined ? source.length : Math.min(source.length, end);
if (begin > end) {
throw new Error("write(): end must be greater than begin");
}
const count = end - begin;
source.copy(begin, end, buffer, position);
position += count;
length = Math.max(length, position);
};
/**
* The wrapped buffer.
* @name MemoryStream.prototype.content
*/
Object.defineProperty(stream, "content", {
get: function() {
return buffer;
}
});
/**
* The number of bytes in the stream's underlying buffer.
* @name MemoryStream.prototype.length
*/
Object.defineProperty(stream, "length", {
get: function() {
checkClosed();
return length
},
set: function(value) {
if (canWrite) {
checkClosed();
length = buffer.length = value;
position = Math.min(position, length);
}
}
});
/**
* The current position of this stream in the wrapped buffer.
* @name MemoryStream.prototype.position
*/
Object.defineProperty(stream, "position", {
get: function() {
checkClosed();
return position;
},
set: function(value) {
checkClosed();
position = Math.min(Math.max(0, value), length);
}
});
/**
* Try to skip over num bytes in the stream. Returns the number of acutal bytes skipped
* or throws an error if the operation could not be completed.
* @name Stream.prototype.skip
* @param {Number} num bytes to skip
* @returns {Number} actual bytes skipped
* @name MemoryStream.prototype.skip
* @function
*/
stream.skip = function(num) {
checkClosed();
num = Math.min(parseInt(num, 10), length - position);
if (isNaN(num)) {
throw new Error("skip() requires a number argument");
} else if (num < 0) {
throw new Error("Argument to skip() must not be negative");
}
position += num;
return num
};
/**
* Flushes the bytes written to the stream to the underlying medium.
* @name MemoryStream.prototype.flush
* @function
*/
stream.flush = function() {
checkClosed();
};
/**
* Closes the stream, freeing the resources it is holding.
* @name MemoryStream.prototype.close
* @function
*/
stream.close = function() {
checkClosed();
closed = true;
};
/**
* Returns true if the stream is closed, false otherwise.
* @name MemoryStream.prototype.closed
* @return {Boolean} true if the stream has been closed
* @function
*/
stream.closed = function() {
return closed;
};
return stream;
}; | A binary stream that reads from and/or writes to an in-memory byte array.
If the constructor is called with a Number argument, a ByteArray with the
given length is allocated and the length of the stream is set to zero.
If the argument is a [binary object](../binary) it will be used as underlying
buffer and the stream length set to the length of the binary object.
If argument is a [ByteArray](../binary#ByteArray), the resulting stream is both
readable, writable, and seekable. If it is a [ByteString](../binary#ByteString),
the resulting stream is readable and seekable but not writable.
If called without argument, a ByteArray of length 1024 is allocated as buffer.
@param {Binary|Number} binaryOrNumber the buffer to use, or the initial
capacity of the buffer to allocate.
@constructor | MemoryStream ( binaryOrNumber ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.seekable = function() {
return false;
}; | Always returns false, as a TextStream is not randomly accessible. | this.seekable ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.readLine = function () {
const line = decoder.readLine(true);
if (line === null)
return "";
return String(line);
}; | Reads a line from this stream. If the end of the stream is reached
before any data is gathered, returns an empty string. Otherwise, returns
the line including only the newline character. Carriage return will be dropped.
@returns {String} the next line | this.readLine ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.iterator = function () {
return this;
}; | Returns this stream.
@return {TextStream} this stream | this.iterator ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.next = function () {
const line = decoder.readLine(false);
if (line == null) {
throw StopIteration;
}
return String(line);
}; | Returns the next line of input without the newline. Throws
`StopIteration` if the end of the stream is reached.
@returns {String} the next line
@example const fs = require('fs');
const txtStream = fs.open('./browserStats.csv', 'r');
try {
while (true) {
console.log(txtStream.next());
}
} catch (e) {
console.log("EOF");
} | this.next ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.forEach = function (callback, thisObj) {
let line = decoder.readLine(false);
while (line != null) {
callback.call(thisObj, line);
line = decoder.readLine(false);
}
}; | Calls `callback` with each line in the input stream.
@param {Function} callback the callback function
@param {Object} [thisObj] optional this-object to use for callback
@example const txtStream = fs.open('./browserStats.csv', 'r');
txtStream.forEach(function(line) {
console.log(line); // Print one single line
}); | this.forEach ( callback , thisObj ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.readLines = function () {
const lines = [];
let line;
do {
line = this.readLine();
if (line.length) {
lines.push(line);
}
} while (line.length);
return lines;
}; | Returns an Array of Strings, accumulated by calling `readLine` until it
returns an empty string. The returned array does not include the final
empty string, but it does include a trailing newline at the end of every
line.
@returns {Array} an array of lines
@example >> const fs = require('fs');
>> const txtStream = fs.open('./sampleData.csv', 'r');
>> const lines = txtStream.readLines();
>> console.log(lines.length + ' lines');
6628 lines | this.readLines ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.read = function () {
return decoder.read();
}; | Read the full stream until the end is reached and return the data read
as string.
@returns {String} | this.read ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.readInto = function () {
throw new Error("Not implemented");
}; | Not implemented for `TextStream`. Calling this method will raise an error. | this.readInto ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.copy = function (output) {
while (true) {
let line = this.readLine();
if (!line.length) {
break;
}
output.write(line).flush();
}
return this;
}; | Reads from this stream with [readLine](#readLine), writing the results
to the target stream and flushing, until the end of this stream is reached.
@param {Stream} output
@return {TextStream} this stream | this.copy ( output ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.write = function () {
if (!io.writable()) {
throw new Error("The TextStream is not writable!");
}
for (let i = 0; i < arguments.length; i++) {
encoder.encode(String(arguments[i]));
}
return this;
}; | Writes all arguments to the stream.
@return {TextStream} this stream
@example >> const fs = require('fs');
>> const txtOutStream = fs.open('./demo.txt', 'w');
>> txtOutStream.write('foo', 'bar', 'baz');
// demo.txt content:
foobarbaz | this.write ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.writeLine = function (line) {
this.write(line + newline);
return this;
}; | Writes the given line to the stream, followed by a newline.
@param {String} line
@return {TextStream} this stream | this.writeLine ( line ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.writeLines = function (lines) {
lines.forEach(this.writeLine, this);
return this;
}; | Writes the given lines to the stream, terminating each line with a newline.
This is a non-standard extension, not part of CommonJS IO/A.
@param {Array} lines
@return {TextStream} this stream | this.writeLines ( lines ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
this.print = function () {
for (let i = 0; i < arguments.length; i++) {
this.write(String(arguments[i]));
if (i < arguments.length - 1) {
this.write(delimiter);
}
}
this.write(newline);
this.flush();
return this;
}; | Writes all argument values as a single line, delimiting the values using
a single blank.
@example >> const fs = require('fs');
>> const txtOutStream = fs.open('./demo.txt', 'w');
>> txtOutStream.print('foo', 'bar', 'baz');
// demo.txt content:
foo bar baz
@return {TextStream} this stream | this.print ( ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
exports.TextStream = function TextStream(io, options, buflen) {
if (this.constructor !== exports.TextStream) {
return new exports.TextStream(io, options, buflen);
}
options = options || {};
const charset = options.charset || "utf8";
const newline = options.hasOwnProperty("newline") ? options.newline : "\n";
const delimiter = options.hasOwnProperty("delimiter") ? options.delimiter : " ";
const DEFAULTSIZE = 8192;
let encoder, decoder;
if (io.readable()) {
decoder = new Decoder(charset, false, buflen || DEFAULTSIZE);
decoder.readFrom(io);
}
if (io.writable()) {
encoder = new Encoder(charset, false, buflen || DEFAULTSIZE);
encoder.writeTo(io);
}
/**
* @see #Stream.prototype.readable
*/
this.readable = function() {
return io.readable();
};
/**
* @see #Stream.prototype.writable
*/
this.writable = function() {
return io.writable();
};
/**
* Always returns false, as a TextStream is not randomly accessible.
*/
this.seekable = function() {
return false;
};
/**
* Reads a line from this stream. If the end of the stream is reached
* before any data is gathered, returns an empty string. Otherwise, returns
* the line including only the newline character. Carriage return will be dropped.
* @returns {String} the next line
*/
this.readLine = function () {
const line = decoder.readLine(true);
if (line === null)
return "";
return String(line);
};
/**
* Returns this stream.
* @return {TextStream} this stream
*/
this.iterator = function () {
return this;
};
/**
* Returns the next line of input without the newline. Throws
* `StopIteration` if the end of the stream is reached.
* @returns {String} the next line
* @example const fs = require('fs');
* const txtStream = fs.open('./browserStats.csv', 'r');
* try {
* while (true) {
* console.log(txtStream.next());
* }
* } catch (e) {
* console.log("EOF");
* }
*/
this.next = function () {
const line = decoder.readLine(false);
if (line == null) {
throw StopIteration;
}
return String(line);
};
/**
* Calls `callback` with each line in the input stream.
* @param {Function} callback the callback function
* @param {Object} [thisObj] optional this-object to use for callback
* @example const txtStream = fs.open('./browserStats.csv', 'r');
* txtStream.forEach(function(line) {
* console.log(line); // Print one single line
* });
*/
this.forEach = function (callback, thisObj) {
let line = decoder.readLine(false);
while (line != null) {
callback.call(thisObj, line);
line = decoder.readLine(false);
}
};
/**
* Returns an Array of Strings, accumulated by calling `readLine` until it
* returns an empty string. The returned array does not include the final
* empty string, but it does include a trailing newline at the end of every
* line.
* @returns {Array} an array of lines
* @example >> const fs = require('fs');
* >> const txtStream = fs.open('./sampleData.csv', 'r');
* >> const lines = txtStream.readLines();
* >> console.log(lines.length + ' lines');
* 6628 lines
*/
this.readLines = function () {
const lines = [];
let line;
do {
line = this.readLine();
if (line.length) {
lines.push(line);
}
} while (line.length);
return lines;
};
/**
* Read the full stream until the end is reached and return the data read
* as string.
* @returns {String}
*/
this.read = function () {
return decoder.read();
};
/**
* Not implemented for `TextStream`. Calling this method will raise an error.
*/
this.readInto = function () {
throw new Error("Not implemented");
};
/**
* Reads from this stream with [readLine](#readLine), writing the results
* to the target stream and flushing, until the end of this stream is reached.
* @param {Stream} output
* @return {TextStream} this stream
*/
this.copy = function (output) {
while (true) {
let line = this.readLine();
if (!line.length) {
break;
}
output.write(line).flush();
}
return this;
};
/**
* Writes all arguments to the stream.
* @return {TextStream} this stream
* @example >> const fs = require('fs');
* >> const txtOutStream = fs.open('./demo.txt', 'w');
* >> txtOutStream.write('foo', 'bar', 'baz');
*
* // demo.txt content:
* foobarbaz
*/
this.write = function () {
if (!io.writable()) {
throw new Error("The TextStream is not writable!");
}
for (let i = 0; i < arguments.length; i++) {
encoder.encode(String(arguments[i]));
}
return this;
};
/**
* Writes the given line to the stream, followed by a newline.
* @param {String} line
* @return {TextStream} this stream
*/
this.writeLine = function (line) {
this.write(line + newline);
return this;
};
/**
* Writes the given lines to the stream, terminating each line with a newline.
* This is a non-standard extension, not part of CommonJS IO/A.
*
* @param {Array} lines
* @return {TextStream} this stream
*/
this.writeLines = function (lines) {
lines.forEach(this.writeLine, this);
return this;
};
/**
* Writes all argument values as a single line, delimiting the values using
* a single blank.
* @example >> const fs = require('fs');
* >> const txtOutStream = fs.open('./demo.txt', 'w');
* >> txtOutStream.print('foo', 'bar', 'baz');
*
* // demo.txt content:
* foo bar baz
* @return {TextStream} this stream
*/
this.print = function () {
for (let i = 0; i < arguments.length; i++) {
this.write(String(arguments[i]));
if (i < arguments.length - 1) {
this.write(delimiter);
}
}
this.write(newline);
this.flush();
return this;
};
/**
* @see #Stream.prototype.flush
*/
this.flush = function () {
io.flush();
return this;
};
/**
* @see #Stream.prototype.close
*/
this.close = function () {
io.close();
};
/**
* If the wrapped stream is a [MemoryStream](#MemoryStream) this contains its
* content decoded to a String with this streams encoding. Otherwise contains
* an empty String.
*/
Object.defineProperty(this, "content", {
get: function() {
const wrappedContent = io.content;
if (!wrappedContent) {
return "";
}
return wrappedContent.decodeToString(charset);
}
});
/**
* The wrapped binary stream.
*/
Object.defineProperty(this, "raw", {
get: function() {
return io;
}
});
return this;
}; | A TextStream implements an I/O stream used to read and write strings. It
wraps a raw Stream and exposes a similar interface.
@param {Stream} io The raw Stream to be wrapped.
@param {Object} options the options object. Supports the following properties:
<ul><li>charset: string containing the name of the encoding to use.
Defaults to "utf8".</li>
<li>newline: string containing the newline character sequence to use in
writeLine() and writeLines(). Defaults to "\n".</li>
<li>delimiter: string containing the delimiter to use in print().
Defaults to " ".</li></ul>
@param {Number} buflen optional buffer size. Defaults to 8192.
@constructor | TextStream ( io , options , buflen ) | javascript | ringo/ringojs | modules/io.js | https://github.com/ringo/ringojs/blob/master/modules/io.js | Apache-2.0 |
const open = exports.open = function(path, options) {
options = checkOptions(options);
const nioPath = resolvePath(path);
let {read, write, append, update, binary, charset} = options;
if (read === true && write === true) {
throw new Error("Cannot open a file for reading and writing at the same time");
}
if (!read && !write && !append && !update) {
read = true;
}
// configure the NIO options
const nioOptions = [];
if (append === true) {
nioOptions.push(StandardOpenOption.APPEND);
}
if (read === true) {
nioOptions.push(StandardOpenOption.READ);
}
if (write === true) {
nioOptions.push(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
const stream = new io.Stream(read ?
Files.newInputStream(nioPath, nioOptions) : Files.newOutputStream(nioPath, nioOptions));
if (binary) {
return stream;
} else if (read || write || append) {
// if charset is undefined, TextStream will use utf8
return new io.TextStream(stream, {charset: charset});
} else if (update) {
// FIXME botic: check for invalid options before returning a stream? See issue #270
throw new Error("update not yet implemented");
}
} | Open the file corresponding to `path` for reading or writing,
depending on the `options` argument. Returns a [binary stream](../io#Stream)
or a [text stream](../io/#TextStream).
The `options` argument may contain the following properties:
- __read__ _(boolean)_ open the file in read-only mode.
- __write__ _(boolean)_ open the file in write mode starting at the beginning of the file.
- __append__ _(boolean)_ open the file in write mode starting at the end of the file.
- __binary__ _(boolean)_ open the file in binary mode.
- __charset__ _(string)_ open the file in text mode using the given encoding. Defaults to UTF-8.
Instead of an `options` object, a string with the following modes can be
provided:
- __r__ _(string)_ equivalent to read-only
- __w__ _(string)_ equivalent to write
- __a__ _(string)_ equivalent to append
- __b__ _(string)_ equivalent to binary
So an `options` object `{ read: true, binary: true }` and the mode string `'rb'` are
functionally equivalent. <em>Note: The options canonical and exclusive proposed by CommonJS are
not supported.</em>
@param {String} path the file path
@param {Object|String} options options as object properties or as mode string
@return {Stream|TextStream} a <code>Stream</code> object in binary mode, otherwise a <code>TextStream</code>
@example // Opens a m4a file in binary mode
const m4aStream = fs.open('music.m4a', {
binary: true,
read: true
});
// The equivalent call with options as string
const m4aStream = fs.open('music.m4a', 'br');
// Opens a text file
const textStream = fs.open('example.txt', { read: true });
// The equivalent call with options as string
const textStream = fs.open('example.txt', 'r'); | exports.open ( path , options ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const openRaw = exports.openRaw = function(path, options) {
const nioPath = resolvePath(path);
options = checkOptions(options || {});
let {read, write, append} = options;
if (!read && !write && !append) {
read = true;
} else if (read === true && write === true) {
throw new Error("Cannot open a file for reading and writing at the same time");
}
// configure the NIO options
const nioOptions = [];
if (append === true) {
nioOptions.push(StandardOpenOption.APPEND);
}
if (read === true) {
nioOptions.push(StandardOpenOption.READ);
}
if (write === true) {
nioOptions.push(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
return new io.Stream(read ? Files.newInputStream(nioPath, nioOptions) : Files.newOutputStream(nioPath, nioOptions));
} | Opens the file corresponding to `path` for reading or writing in binary
mode. The `options` argument may contain the following properties:
- __read__ _(boolean)_ open the file in read-only mode. (default)
- __write__ _(boolean)_ open the file in write mode starting at the beginning of the file.
- __append__ _(boolean)_ open the file in write mode starting at the end of the file.
@param {String} path the file path
@param {Object} options options
@returns {Stream}
@see #open | exports.openRaw ( path , options ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const copy = exports.copy = function(from, to) {
const sourcePath = resolvePath(from);
const targetPath = resolvePath(to);
if (!Files.exists(sourcePath) || Files.isDirectory(sourcePath)) {
throw new Error(sourcePath + " does not exist!");
}
Files.copy(sourcePath, targetPath, [StandardCopyOption.REPLACE_EXISTING]);
} | Read data from one file and write it into another using binary mode.
Replaces an existing file if it exists.
@param {String} from original file
@param {String} to copy to create
@example // Copies file from a temporary upload directory into /var/www
fs.copy('/tmp/uploads/fileA.txt', '/var/www/fileA.txt'); | exports.copy ( from , to ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const copyTree = exports.copyTree = function(from, to) {
const source = resolvePath(from);
const target = resolvePath(to);
if (String(target) === String(source)) {
throw new Error("Source and target files are equal in copyTree.");
} else if (String(target).indexOf(String(source) + SEPARATOR) === 0) {
throw new Error("Target is a child of source in copyTree");
}
if (Files.isDirectory(source)) {
makeTree(target);
list(source).forEach(file => {
const s = join(source.toString(), file);
const t = join(target.toString(), file);
if (isLink(s)) {
symbolicLink(readLink(s), t);
} else {
copyTree(s, t);
}
});
} else {
copy(source.toString(), target.toString());
}
} | Copy files from a source path to a target path. Files of the below the
source path are copied to the corresponding locations relative to the target
path, symbolic links to directories are copied but not traversed into.
@param {String} from the original tree
@param {String} to the destination for the copy
@example Before:
βββ foo
βββ bar
βΒ Β βββ example.m4a
βββ baz
// Copy foo
fs.copyTree('./foo', './foo2');
After:
βββ foo
βΒ Β βββ bar
βΒ Β βΒ Β βββ example.m4a
βΒ Β βββ baz
βββ foo2
βββ bar
βΒ Β βββ example.m4a
βββ baz | exports.copyTree ( from , to ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const makeTree = exports.makeTree = function(path) {
Files.createDirectories(resolvePath(path));
} | Create the directory specified by `path` including any missing parent
directories.
@param {String} path the path of the tree to create
@example Before:
βββ foo
fs.makeTree('foo/bar/baz/');
After:
βββ foo
βββ bar
βββ baz | exports.makeTree ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const listDirectoryTree = exports.listDirectoryTree = function(path) {
path = path === '' ? '.' : String(path);
list(path).reduce((result, child) => {
const childPath = join(path, child);
if (isDirectory(childPath)) {
if (!isLink(childPath)) {
result.push.apply(result,
listDirectoryTree(childPath).map(p => join(child, p)));
} else { // Don't follow symlinks.
result.push(child);
}
}
return result;
}, ['']);
return result.sort();
} | Return an array with all directories below (and including) the given path,
as discovered by depth-first traversal. Entries are in lexically sorted
order within directories. Symbolic links to directories are not traversed
into.
@param {String} path the path to discover
@returns {Array} array of strings with all directories lexically sorted
@example // File system tree of the current working directory:
.
βββ foo
βββ bar
βββ baz
fs.listDirectoryTree('.');
// returned array:
[ '', 'foo', 'foo/bar', 'foo/bar/baz' ] | exports.listDirectoryTree ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const listTree = exports.listTree = function(path) {
path = path === '' ? '.' : String(path);
return list(path).reduce((result, child) => {
const childPath = join(path, child);
// Don't follow directory symlinks, but include them
if (isDirectory(childPath) && !isLink(childPath)) {
result.push.apply(result,
listTree(childPath).map(p => join(child, p)));
} else {
// Add file or symlinked directory.
result.push(child);
}
return result;
}, ['']).sort();
} | Return an array with all paths (files, directories, etc.) below (and
including) the given path, as discovered by depth-first traversal. Entries
are in lexically sorted order within directories. Symbolic links to
directories are returned but not traversed into.
@param {String} path the path to list
@returns {Array} array of strings with all discovered paths
@example // File system tree of the current working directory:
.
βββ foo
βΒ Β βββ bar
βΒ Β βββ baz
βββ musicfile.m4a
βββ test.txt
fs.listTree('.');
// returned array:
['', 'foo', 'foo/bar', 'foo/bar/baz', 'musicfile.m4a', 'test.txt'] | exports.listTree ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isAbsolute = exports.isAbsolute = function(path) {
return getPath(path).isAbsolute();
} | Check whether the given pathname is absolute. This is a non-standard extension,
not part of CommonJS Filesystem/A.
@param {String} path the path to check
@returns {Boolean} true if path is absolute, false if not
@example >> fs.isAbsolute('../../');
false
>> fs.isAbsolute('/Users/username/Desktop/example.txt');
true | exports.isAbsolute ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const isRelative = exports.isRelative = function(path) {
return !isAbsolute(path);
} | Check whether the given pathname is relative (i.e. not absolute). This is a non-standard
extension, not part of CommonJS Filesystem/A.
@param {String} path the path to check
@returns {Boolean} true if path is relative, false if not | exports.isRelative ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const absolute = exports.absolute = function(path) {
return resolve(workingDirectory(), path);
} | Make the given path absolute by resolving it against the current working
directory.
@param {String} path the path to resolve
@returns {String} the absolute path
@example >> fs.absolute('foo/bar/test.txt');
'/Users/username/Desktop/working-directory/foo/bar/test.txt' | exports.absolute ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const base = exports.base = function(path, ext) {
const name = arrays.peek(split(path));
if (ext && name) {
const diff = name.length - ext.length;
if (diff > -1 && name.lastIndexOf(ext) === diff) {
return name.substring(0, diff);
}
}
return name;
} | Return the basename of the given path. That is the path with any leading
directory components removed. If specified, also remove a trailing
extension.
@param {String} path the full path
@param {String} ext an optional extension to remove
@returns {String} the basename
@example >> fs.base('/a/b/c/foosomeext', 'someext');
'foo' | exports.base ( path , ext ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
const directory = exports.directory = function(path) {
return (getPath(path).getParent() || getPath('.')).toString();
} | Return the dirname of the given path. That is the path with any trailing
non-directory component removed.
@param {String} path
@returns {String} the parent directory path
@example >> fs.directory('/Users/username/Desktop/example/test.txt');
'/Users/username/Desktop/example' | exports.directory ( path ) | javascript | ringo/ringojs | modules/fs.js | https://github.com/ringo/ringojs/blob/master/modules/fs.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.