diff options
author | Nayeem Rahman <nayeemrmn99@gmail.com> | 2020-10-19 13:36:53 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-10-19 14:36:53 +0200 |
commit | 19b918d112c786b1db17fe2d83be79f1114ba240 (patch) | |
tree | b8ae7e1f5aa4b70570245b61c504c5c46e2e78e8 /std/path/win32.ts | |
parent | 342b151b5d9d6c97926588dd118b59032f3b0e40 (diff) |
feat(std/path): Add toFileUrl() (#7971)
Diffstat (limited to 'std/path/win32.ts')
-rw-r--r-- | std/path/win32.ts | 31 |
1 files changed, 26 insertions, 5 deletions
diff --git a/std/path/win32.ts b/std/path/win32.ts index 246c18a97..1684a2c45 100644 --- a/std/path/win32.ts +++ b/std/path/win32.ts @@ -917,11 +917,8 @@ export function fromFileUrl(url: string | URL): string { throw new TypeError("Must be a file URL."); } let path = decodeURIComponent( - url.pathname - .replace(/^\/*([A-Za-z]:)(\/|$)/, "$1/") - .replace(/\//g, "\\") - .replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), - ); + url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), + ).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\"); if (url.hostname != "") { // Note: The `URL` implementation guarantees that the drive letter and // hostname are mutually exclusive. Otherwise it would not have been valid @@ -930,3 +927,27 @@ export function fromFileUrl(url: string | URL): string { } return path; } + +/** Converts a path string to a file URL. + * + * toFileUrl("\\home\\foo"); // new URL("file:///home/foo") + * toFileUrl("C:\\Users\\foo"); // new URL("file:///C:/Users/foo") + * toFileUrl("\\\\localhost\\home\\foo"); // new URL("file://localhost/home/foo") + */ +export function toFileUrl(path: string): URL { + if (!isAbsolute(path)) { + throw new TypeError("Must be an absolute path."); + } + const [, hostname, pathname] = path.match( + /^(?:[/\\]{2}([^/\\]+)(?=[/\\][^/\\]))?(.*)/, + )!; + const url = new URL("file:///"); + url.pathname = pathname.replace(/%/g, "%25"); + if (hostname != null) { + url.hostname = hostname; + if (!url.hostname) { + throw new TypeError("Invalid hostname."); + } + } + return url; +} |