summaryrefslogtreecommitdiff
path: root/cli/js/util.ts
diff options
context:
space:
mode:
authorRiver <22485304+actual-size@users.noreply.github.com>2020-06-12 02:36:20 +1000
committerGitHub <noreply@github.com>2020-06-11 12:36:20 -0400
commit818a8010928cb8cef0b7043bd881c8cdce9b6efc (patch)
tree1502e74c9eb01901df8da118257d60d4f962b0e4 /cli/js/util.ts
parent813210d4337bf6e174f1da1f1a6c6fb9b073afa2 (diff)
feat: URL support in Deno filesystem methods (#5990)
Diffstat (limited to 'cli/js/util.ts')
-rw-r--r--cli/js/util.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/cli/js/util.ts b/cli/js/util.ts
index 309bfcd0c..c50a4cdcb 100644
--- a/cli/js/util.ts
+++ b/cli/js/util.ts
@@ -1,4 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
+import { build } from "./build.ts";
+import { exposeForTest } from "./internals.ts";
let logDebug = false;
let logSource = "JS";
@@ -78,3 +80,49 @@ export function immutableDefine(
writable: false,
});
}
+
+function pathFromURLWin32(url: URL): string {
+ if (url.hostname !== "") {
+ //TODO(actual-size) Node adds a punycode decoding step, we should consider adding this
+ return `\\\\${url.hostname}${url.pathname}`;
+ }
+
+ const validPath = /^\/(?<driveLetter>[A-Za-z]):\//;
+ const matches = validPath.exec(url.pathname);
+
+ if (!matches?.groups?.driveLetter) {
+ throw new TypeError("A URL with the file schema must be absolute.");
+ }
+
+ const pathname = url.pathname.replace(/\//g, "\\");
+ // we don't want a leading slash on an absolute path in Windows
+ return pathname.slice(1);
+}
+
+function pathFromURLPosix(url: URL): string {
+ if (url.hostname !== "") {
+ throw new TypeError(`Host must be empty.`);
+ }
+
+ return decodeURIComponent(url.pathname);
+}
+
+export function pathFromURL(pathOrUrl: string | URL): string {
+ if (typeof pathOrUrl == "string") {
+ try {
+ pathOrUrl = new URL(pathOrUrl);
+ } catch {}
+ }
+ if (pathOrUrl instanceof URL) {
+ if (pathOrUrl.protocol != "file:") {
+ throw new TypeError("Must be a path string or file URL.");
+ }
+
+ return build.os == "windows"
+ ? pathFromURLWin32(pathOrUrl)
+ : pathFromURLPosix(pathOrUrl);
+ }
+ return pathOrUrl;
+}
+
+exposeForTest("pathFromURL", pathFromURL);