Skip to content

Commit b3f2664

Browse files
committed
feat: add tilde expansion to expand()
This adds tilde expansion to the expand() function. Arguments starting with '~/' will have the tilde expanded to the user's home directory, as with Bash.
1 parent 15261f8 commit b3f2664

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/common.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,18 @@ function ShellString(str) {
5353
}
5454
exports.ShellString = ShellString;
5555

56+
// Return the home directory in a platform-agnostic way, with consideration for
57+
// older versions of node
58+
function getUserHome() {
59+
var result;
60+
if (os.homedir)
61+
result = os.homedir(); // node 3+
62+
else
63+
result = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
64+
return result;
65+
}
66+
exports.getUserHome = getUserHome;
67+
5668
// Returns {'alice': true, 'bob': false} when passed a dictionary, e.g.:
5769
// parseOptions('-a', {'a':'alice', 'b':'bob'});
5870
function parseOptions(str, map) {
@@ -187,6 +199,14 @@ function wrap(cmd, fn, options) {
187199
} else {
188200
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
189201
args.unshift(''); // only add dummy option if '-option' not already present
202+
// Expand the '~' if appropriate
203+
var homeDir = getUserHome();
204+
args = args.map(function(arg) {
205+
if (typeof arg === 'string' && arg.slice(0, 2) === '~/' || arg === '~')
206+
return arg.replace(/^~/, homeDir);
207+
else
208+
return arg;
209+
});
190210
retValue = fn.apply(this, args);
191211
}
192212
} catch (e) {

test/cd.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ var shell = require('..');
22

33
var assert = require('assert'),
44
path = require('path'),
5-
fs = require('fs');
5+
fs = require('fs'),
6+
common = require('../src/common');
67

78
shell.config.silent = true;
89

@@ -54,4 +55,12 @@ shell.cd('../tmp');
5455
assert.equal(shell.error(), null);
5556
assert.equal(fs.existsSync('file1'), true);
5657

58+
// Test tilde expansion
59+
60+
shell.cd('~');
61+
assert.equal(process.cwd(), common.getUserHome());
62+
shell.cd('..');
63+
shell.cd('~'); // Change back to home
64+
assert.equal(process.cwd(), common.getUserHome());
65+
5766
shell.exit(123);

0 commit comments

Comments
 (0)