From fc530ea1dc58d14850c7d72b32ae001387c19400 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 5 Jul 2019 13:49:40 +0200 Subject: [PATCH 1/2] path: using .relative() should not return a trailing slash Resolving a path against root with `path.relative()` should not include a trailing slash. Fixes: https://github.com/nodejs/node/issues/28549 --- lib/path.js | 15 ++++++++++----- test/parallel/test-path-relative.js | 3 ++- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/path.js b/lib/path.js index 2301a6ebb8321f..f7a8612933ad76 100644 --- a/lib/path.js +++ b/lib/path.js @@ -1090,11 +1090,16 @@ const posix = { // For example: from='/'; to='/foo' return to.slice(toStart + i); } - } else if (fromLen > length && - from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo/bar'; to='/' + lastCommonSep = 0; + } } } diff --git a/test/parallel/test-path-relative.js b/test/parallel/test-path-relative.js index 599381cdccfcb9..72f862b6df764e 100644 --- a/test/parallel/test-path-relative.js +++ b/test/parallel/test-path-relative.js @@ -47,7 +47,8 @@ const relativeTests = [ ['/foo/bar/baz-quux', '/foo/bar/baz', '../baz'], ['/foo/bar/baz', '/foo/bar/baz-quux', '../baz-quux'], ['/baz-quux', '/baz', '../baz'], - ['/baz', '/baz-quux', '../baz-quux'] + ['/baz', '/baz-quux', '../baz-quux'], + ['/page1/page2/foo', '/', '../../..'] ] ] ]; From 58edefdc841ae33c18fa5426419d3a8847e5a827 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Fri, 5 Jul 2019 14:34:25 +0200 Subject: [PATCH 2/2] path: move branch to the correct location This code branch only makes sense when i === length. Otherwise it'll already be handled. --- lib/path.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/path.js b/lib/path.js index f7a8612933ad76..e278c891482070 100644 --- a/lib/path.js +++ b/lib/path.js @@ -518,11 +518,11 @@ const win32 = { lastCommonSep = 3; } } + if (lastCommonSep === -1) + lastCommonSep = 0; } let out = ''; - if (lastCommonSep === -1) - lastCommonSep = 0; // Generate the relative path based on the path difference between `to` and // `from` for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {