-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargs.ts
73 lines (69 loc) · 1.9 KB
/
args.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
// deno-lint-ignore-file no-explicit-any
/**
* @file args.ts
* @author Brandon Kalinowski
* @copyright 2020-2024 Brandon Kalinowski
* @description Utilities for parsing CLI arguments.
* @license MIT
*/
import { parseArgs } from "jsr:@std/[email protected]/parse-args";
import { JSON_SCHEMA, parse } from "jsr:@std/[email protected]";
/**
* If the value is '-' stdin is read and returned.
* If stdin fails to be read, undefined is returned
* Otherwise the value is returned.
*/
export function textOrStdIn(value: string) {
if (value === "-") {
const buf = new Uint8Array(1024);
try {
const n = Deno.stdin.readSync(buf);
if (n === null) {
return undefined;
} else {
return new TextDecoder().decode(buf.subarray(0, n));
}
} catch (_e) {
return undefined;
}
}
return value;
}
export const looksLikeYamlRe = /(" *?:)|(: )/;
/**
* getArgsObject is a helper utility like flags.parse().
* It parses flags. Flag values that look like YAML will be parsed to their object form.
* @param yamlKeys Disable YAML inference and always parse these values as YAML.
* @param argsArray Specify to parse an alternative value instead of Deno.args.
*/
export function getArgsObject(
yamlKeys?: Set<string>,
argsArray?: string[],
): Record<string, any> {
const isYaml = yamlKeys
? (key: string, _: string) => {
return yamlKeys.has(key);
}
: (_: string, value: string) => {
return !!looksLikeYamlRe.exec(value);
};
const rawArgs = parseArgs(argsArray || Deno.args);
const parsedArgs: any = {};
Object.entries(rawArgs).forEach(([key, rawValue]) => {
let value = textOrStdIn(rawValue);
if (value !== undefined) {
if (isYaml(key, value)) {
try {
value = parse(value, { schema: JSON_SCHEMA }) as string;
} catch (err) {
// ignore failure if we inferred possible YAML key
if (!yamlKeys) {
throw err;
}
}
}
parsedArgs[key] = value;
}
});
return parsedArgs;
}