mirror of
https://github.com/shelljs/shelljs.git
synced 2026-01-18 16:03:37 +00:00
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:
parent
15261f846c
commit
b3f266469b
@ -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) {
|
||||
|
||||
11
test/cd.js
11
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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user