Skip to content

Commit

Permalink
[Refactor] make maybeUnwrapSymlink
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Jul 29, 2019
1 parent ba82ea8 commit 36c0abc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 19 deletions.
27 changes: 19 additions & 8 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ var defaultIsDir = function isDirectory(dir, cb) {
});
};

var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
if (opts && opts.preserveSymlinks === false) {
fs.realpath(x, function (realPathErr, realPath) {
if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
else cb(null, realPathErr ? x : realPath);
});
} else {
cb(null, x);
}
};

module.exports = function resolve(x, options, callback) {
var cb = callback;
var opts = options;
Expand Down Expand Up @@ -54,14 +65,14 @@ module.exports = function resolve(x, options, callback) {
// ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
var absoluteStart = path.resolve(basedir);

if (opts.preserveSymlinks === false) {
fs.realpath(absoluteStart, function (realPathErr, realStart) {
if (realPathErr && realPathErr.code !== 'ENOENT') cb(err);
else init(realPathErr ? absoluteStart : realStart);
});
} else {
init(absoluteStart);
}
maybeUnwrapSymlink(
absoluteStart,
opts,
function (err, realStart) {
if (err) cb(err);
else init(realStart);
}
);

var res;
function init(basedir) {
Expand Down
25 changes: 14 additions & 11 deletions lib/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ var defaultIsDir = function isDirectory(dir) {
return stat.isDirectory();
};

var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts) {
if (opts && opts.preserveSymlinks === false) {
try {
return fs.realpathSync(x);
} catch (realPathErr) {
if (realPathErr.code !== 'ENOENT') {
throw realPathErr;
}
}
}
return x;
};

module.exports = function (x, options) {
if (typeof x !== 'string') {
throw new TypeError('Path must be a string.');
Expand All @@ -42,17 +55,7 @@ module.exports = function (x, options) {
opts.paths = opts.paths || [];

// ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
var absoluteStart = path.resolve(basedir);

if (opts.preserveSymlinks === false) {
try {
absoluteStart = fs.realpathSync(absoluteStart);
} catch (realPathErr) {
if (realPathErr.code !== 'ENOENT') {
throw realPathErr;
}
}
}
var absoluteStart = maybeUnwrapSymlink(path.resolve(basedir), opts);

if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
var res = path.resolve(absoluteStart, x);
Expand Down

0 comments on commit 36c0abc

Please sign in to comment.