-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.ts
78 lines (61 loc) · 1.58 KB
/
input.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
import { normalize } from "./path.ts";
export function envName(name: string): string {
return `INPUT_${name.toUpperCase()}`;
}
export function get<T = unknown>(name: string): T {
const inputEnvName = envName(name);
if (!Deno.env.has(inputEnvName)) {
throw new Error(`Missing required environment variable: ${inputEnvName}`);
}
const value = Deno.env.get(inputEnvName) as string ?? "";
if (value.startsWith("json:")) {
return JSON.parse(value.substring(5)) as T;
}
return value as T;
}
export function getOptional<T = unknown>(
name: string,
fallback: T | undefined = undefined,
): T | undefined {
try {
const name_ = envName(name);
// if they don't have permission to read the env variable, return the fallback
if (
Deno.permissions.querySync({ name: "env", variable: name_ })
.state !== "granted"
) {
return fallback;
}
const value = get<T>(name);
return value === undefined ? fallback : value;
} catch {
return fallback;
}
}
export function getBoolean(name: string, strict = true): boolean {
const value = strict ? get(name) : getOptional(name);
if (typeof value === "boolean") {
return value;
}
if (typeof value === "string") {
switch (value.toLowerCase()) {
case "1":
case "yes":
case "true":
return true;
default:
return false;
}
}
if (typeof value !== "number") {
return false;
}
return value === 1;
}
export async function getNormalizedPath(
name: string,
): Promise<string> {
return await normalize(
get<string>(name),
);
}