-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path_util.ts
102 lines (93 loc) · 2.4 KB
/
_util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { path } from "./deps.ts";
/**
* returns true if path can be parsed by URL
*
* `
* isURL("https://foo") // output: true
* isURL("/foo/bar") // output: false
* `
*/
export function isURL(filepath: string) {
try {
new URL(filepath);
return true;
} catch {
return false;
}
}
export function isFileURL(filepath: string) {
try {
const url = new URL(filepath);
return url.protocol === "file:";
} catch {
return false;
}
}
export function timestamp(time: number) {
const delta = Math.ceil(performance.now() - time);
const unit = "ms";
return `${delta}${unit}`;
}
export function formatBytes(bytes: number) {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const unit = units[i];
const decimal = i > 2 ? 2 : 0;
const value = bytes / Math.pow(k, i);
return `${value.toFixed(decimal)} ${unit}`;
}
const encoder = new TextEncoder();
export async function createSha256(input: string) {
const hashBuffer = await crypto.subtle.digest(
"SHA-256",
encoder.encode(input),
);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
return hex;
}
export function parsePaths(paths: (string | number)[], root: string) {
const regex = /^(?<input>.+?)(?:(?:\=)(["']?)(?<output>.+)\2)?$/;
const inputs: string[] = [];
const outputMap: Record<string, string> = {};
paths.forEach((entry) => {
let { input, output } = regex.exec(entry as string)?.groups || {};
if (!isURL(input)) {
input = path.toFileUrl(path.resolve(Deno.cwd(), input)).href;
}
inputs.push(input);
if (output) {
if (!isURL(output)) {
output =
path.toFileUrl(path.join(path.resolve(Deno.cwd(), root), output))
.href;
}
outputMap[input] = output;
}
});
return { inputs, outputMap };
}
export async function exists(filename: string) {
try {
await Deno.stat(filename);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}
export function existsSync(filename: string) {
try {
Deno.statSync(filename);
return true;
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return false;
}
throw error;
}
}