var common = require('./common');
var _cd = require('./cd');
var path = require('path');
common.register('dirs', _dirs, {
wrapOutput: false,
});
common.register('pushd', _pushd, {
wrapOutput: false,
});
common.register('popd', _popd, {
wrapOutput: false,
});
var _dirStack = [];
function _isStackIndex(index) {
return (/^[\-+]\d+$/).test(index);
}
function _parseStackIndex(index) {
if (_isStackIndex(index)) {
if (Math.abs(index) < _dirStack.length + 1) { return (/^-/).test(index) ? Number(index) - 1 : Number(index);
}
common.error(index + ': directory stack index out of range');
} else {
common.error(index + ': invalid number');
}
}
function _actualDirStack() {
return [process.cwd()].concat(_dirStack);
}
function _pushd(options, dir) {
if (_isStackIndex(options)) {
dir = options;
options = '';
}
options = common.parseOptions(options, {
'n': 'no-cd',
'q': 'quiet',
});
var dirs = _actualDirStack();
if (dir === '+0') {
return dirs; } else if (!dir) {
if (dirs.length > 1) {
dirs = dirs.splice(1, 1).concat(dirs);
} else {
return common.error('no other directory');
}
} else if (_isStackIndex(dir)) {
var n = _parseStackIndex(dir);
dirs = dirs.slice(n).concat(dirs.slice(0, n));
} else {
if (options['no-cd']) {
dirs.splice(1, 0, dir);
} else {
dirs.unshift(dir);
}
}
if (options['no-cd']) {
dirs = dirs.slice(1);
} else {
dir = path.resolve(dirs.shift());
_cd('', dir);
}
_dirStack = dirs;
return _dirs(options.quiet ? '-q' : '');
}
exports.pushd = _pushd;
function _popd(options, index) {
if (_isStackIndex(options)) {
index = options;
options = '';
}
options = common.parseOptions(options, {
'n': 'no-cd',
'q': 'quiet',
});
if (!_dirStack.length) {
return common.error('directory stack empty');
}
index = _parseStackIndex(index || '+0');
if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) {
index = index > 0 ? index - 1 : index;
_dirStack.splice(index, 1);
} else {
var dir = path.resolve(_dirStack.shift());
_cd('', dir);
}
return _dirs(options.quiet ? '-q' : '');
}
exports.popd = _popd;
function _dirs(options, index) {
if (_isStackIndex(options)) {
index = options;
options = '';
}
options = common.parseOptions(options, {
'c': 'clear',
'q': 'quiet',
});
if (options.clear) {
_dirStack = [];
return _dirStack;
}
var stack = _actualDirStack();
if (index) {
index = _parseStackIndex(index);
if (index < 0) {
index = stack.length + index;
}
if (!options.quiet) {
common.log(stack[index]);
}
return stack[index];
}
if (!options.quiet) {
common.log(stack.join(' '));
}
return stack;
}
exports.dirs = _dirs;