diff --git a/src/common.js b/src/common.js index b207233..16c3c27 100644 --- a/src/common.js +++ b/src/common.js @@ -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) { diff --git a/test/cd.js b/test/cd.js index ba57564..d06c09a 100644 --- a/test/cd.js +++ b/test/cd.js @@ -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);