Skip to content

Commit 1979d07

Browse files
committed
Adding previousDir field to common.state to allow cd('-') to work like Bash
1 parent 5ea67cf commit 1979d07

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

src/cd.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,20 @@ function _cd(options, dir) {
88
if (!dir)
99
common.error('directory not specified');
1010

11+
if (dir === '-') {
12+
if (!common.state.previousDir)
13+
common.error('could not find previous directory');
14+
else
15+
dir = common.state.previousDir;
16+
}
17+
1118
if (!fs.existsSync(dir))
1219
common.error('no such file or directory: ' + dir);
1320

1421
if (!fs.statSync(dir).isDirectory())
1522
common.error('not a directory: ' + dir);
1623

24+
common.state.previousDir = process.cwd();
1725
process.chdir(dir);
1826
}
1927
module.exports = _cd;

src/common.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ exports.config = config;
1212
var state = {
1313
error: null,
1414
currentCmd: 'shell.js',
15+
previousDir: null,
1516
tempDir: null
1617
};
1718
exports.state = state;
@@ -185,7 +186,7 @@ function wrap(cmd, fn, options) {
185186
if (options && options.notUnix) {
186187
retValue = fn.apply(this, args);
187188
} else {
188-
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
189+
if (args.length === 0 || typeof args[0] !== 'string' || args[0].length <= 1 || args[0][0] !== '-')
189190
args.unshift(''); // only add dummy option if '-option' not already present
190191
retValue = fn.apply(this, args);
191192
}

test/cd.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ assert.equal(fs.existsSync('resources/file1'), true); // sanity check
2727
shell.cd('resources/file1'); // file, not dir
2828
assert.ok(shell.error());
2929

30+
shell.cd('-'); // Haven't changed yet, so there is no previous directory
31+
assert.ok(shell.error());
32+
3033
//
3134
// Valids
3235
//
@@ -41,6 +44,12 @@ shell.cd('/');
4144
assert.equal(shell.error(), null);
4245
assert.equal(process.cwd(), path.resolve('/'));
4346

47+
shell.cd(cur);
48+
shell.cd('/');
49+
shell.cd('-');
50+
assert.equal(shell.error(), null);
51+
assert.equal(process.cwd(), path.resolve(cur));
52+
4453
// cd + other commands
4554

4655
shell.cd(cur);

0 commit comments

Comments
 (0)