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.
This commit is contained in:
Nate Fischer 2016-01-18 17:29:07 -08:00
parent 15261f846c
commit b3f266469b
2 changed files with 30 additions and 1 deletions

View File

@ -53,6 +53,18 @@ function ShellString(str) {
}
exports.ShellString = ShellString;
// Return the home directory in a platform-agnostic way, with consideration for
// older versions of node
function getUserHome() {
var result;
if (os.homedir)
result = os.homedir(); // node 3+
else
result = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
return result;
}
exports.getUserHome = getUserHome;
// Returns {'alice': true, 'bob': false} when passed a dictionary, e.g.:
// parseOptions('-a', {'a':'alice', 'b':'bob'});
function parseOptions(str, map) {
@ -187,6 +199,14 @@ function wrap(cmd, fn, options) {
} else {
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
args.unshift(''); // only add dummy option if '-option' not already present
// Expand the '~' if appropriate
var homeDir = getUserHome();
args = args.map(function(arg) {
if (typeof arg === 'string' && arg.slice(0, 2) === '~/' || arg === '~')
return arg.replace(/^~/, homeDir);
else
return arg;
});
retValue = fn.apply(this, args);
}
} catch (e) {

View File

@ -2,7 +2,8 @@ var shell = require('..');
var assert = require('assert'),
path = require('path'),
fs = require('fs');
fs = require('fs'),
common = require('../src/common');
shell.config.silent = true;
@ -54,4 +55,12 @@ shell.cd('../tmp');
assert.equal(shell.error(), null);
assert.equal(fs.existsSync('file1'), true);
// Test tilde expansion
shell.cd('~');
assert.equal(process.cwd(), common.getUserHome());
shell.cd('..');
shell.cd('~'); // Change back to home
assert.equal(process.cwd(), common.getUserHome());
shell.exit(123);