Skip to content

Commit 871396c

Browse files
omsmithrvagg
authored andcommitted
path: fix win32 relative() for UNC paths
win32 normalize() will output a trailing '\' for some UNC paths. trim them before processing Change by @mscdex Add basic UNC path tests to win32 relative() PR-URL: #5456 Reviewed-By: Brian White <mscdex@mscdex.net> Reviewed-By: Roman Reiss <me@silverwind.io>
1 parent 91782f1 commit 871396c

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

lib/path.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,12 @@ const win32 = {
585585
if (from.charCodeAt(fromStart) !== 92/*\*/)
586586
break;
587587
}
588+
// Trim trailing backslashes (applicable to UNC paths only)
588589
var fromEnd = from.length;
590+
for (; fromEnd - 1 > fromStart; --fromEnd) {
591+
if (from.charCodeAt(fromEnd - 1) !== 92/*\*/)
592+
break;
593+
}
589594
var fromLen = (fromEnd - fromStart);
590595

591596
// Trim any leading backslashes
@@ -594,7 +599,12 @@ const win32 = {
594599
if (to.charCodeAt(toStart) !== 92/*\*/)
595600
break;
596601
}
602+
// Trim trailing backslashes (applicable to UNC paths only)
597603
var toEnd = to.length;
604+
for (; toEnd - 1 > toStart; --toEnd) {
605+
if (to.charCodeAt(toEnd - 1) !== 92/*\*/)
606+
break;
607+
}
598608
var toLen = (toEnd - toStart);
599609

600610
// Compare paths to find the longest common path from root
@@ -662,12 +672,12 @@ const win32 = {
662672
// Lastly, append the rest of the destination (`to`) path that comes after
663673
// the common path parts
664674
if (out.length > 0)
665-
return out + toOrig.slice(toStart + lastCommonSep);
675+
return out + toOrig.slice(toStart + lastCommonSep, toEnd);
666676
else {
667677
toStart += lastCommonSep;
668678
if (toOrig.charCodeAt(toStart) === 92/*\*/)
669679
++toStart;
670-
return toOrig.slice(toStart);
680+
return toOrig.slice(toStart, toEnd);
671681
}
672682
},
673683

test/parallel/test-path.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,12 @@ const relativeTests = [
471471
['c:/aaaaa/', 'c:/aaaa/cccc', '..\\aaaa\\cccc'],
472472
['C:\\foo\\bar\\baz\\quux', 'C:\\', '..\\..\\..\\..'],
473473
['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json'],
474-
['C:\\foo\\bar\\baz-quux', 'C:\\foo\\bar\\baz', '..\\baz']
474+
['C:\\foo\\bar\\baz-quux', 'C:\\foo\\bar\\baz', '..\\baz'],
475+
['C:\\foo\\bar\\baz', 'C:\\foo\\bar\\baz-quux', '..\\baz-quux'],
476+
['\\\\foo\\bar', '\\\\foo\\bar\\baz', 'baz'],
477+
['\\\\foo\\bar\\baz', '\\\\foo\\bar', '..'],
478+
['\\\\foo\\bar\\baz-quux', '\\\\foo\\bar\\baz', '..\\baz'],
479+
['\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz-quux', '..\\baz-quux']
475480
]
476481
],
477482
[ path.posix.relative,

0 commit comments

Comments
 (0)