-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
print_task.ts
166 lines (157 loc) 路 5.53 KB
/
print_task.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import {cyan, gray, green, red} from 'kleur/colors';
import type {Logger} from '@ryanatkn/belt/log.js';
import {plural} from '@ryanatkn/belt/string.js';
import {print_value} from '@ryanatkn/belt/print.js';
import {ZodFirstPartyTypeKind, type ZodObjectDef, type ZodTypeAny, type ZodTypeDef} from 'zod';
import type {Arg_Schema} from './args.js';
import {load_modules} from './modules.js';
import {load_task_module, type Task_Module_Meta} from './task_module.js';
export const log_available_tasks = async (
log: Logger,
dir_label: string,
source_ids_by_input_path: Map<string, string[]>,
print_intro = true,
): Promise<void> => {
const source_ids = Array.from(source_ids_by_input_path.values()).flat();
if (source_ids.length) {
// Load all of the tasks so we can print their summary, and args for the `--help` flag.
const load_modules_result = await load_modules(source_ids_by_input_path, load_task_module);
if (!load_modules_result.ok) {
log_error_reasons(log, load_modules_result.reasons);
process.exit(1);
}
const printed: string[] = [
`${print_intro ? '\n\n' : ''}${source_ids.length} task${plural(
source_ids.length,
)} in ${dir_label}:\n`,
];
if (print_intro) {
printed.unshift(
`\n\n${gray('Run a task:')} gro [name]`,
`\n${gray('View help:')} gro [name] --help`,
);
}
const longest_task_name = to_max_length(load_modules_result.modules, (m) => m.name);
for (const meta of load_modules_result.modules) {
printed.push(
'\n' + cyan(pad(meta.name, longest_task_name)),
' ',
meta.mod.task.summary || '',
);
}
log[print_intro ? 'info' : 'plain'](printed.join('') + '\n');
} else {
log.info(`No tasks found in ${dir_label}.`);
}
};
export const log_error_reasons = (log: Logger, reasons: string[]): void => {
for (const reason of reasons) {
log.error(red(reason));
}
};
const ARGS_PROPERTY_NAME = '[...args]';
export const print_task_help = (log: Logger, meta: Task_Module_Meta): void => {
const {
name,
mod: {task},
} = meta;
const printed: string[] = [];
printed.push(
cyan(name),
'help',
cyan(`\n\ngro ${name}`) + `: ${task.summary || '(no summary available)'}\n`,
);
if (task.Args) {
const properties = to_arg_properties(task.Args._def, meta);
// TODO hacky padding for some quick and dirty tables
const longest_task_name = Math.max(
ARGS_PROPERTY_NAME.length,
to_max_length(properties, (p) => p.name),
);
const longest_type = to_max_length(properties, (p) => p.schema.type);
const longest_default = to_max_length(properties, (p) => print_value(p.schema.default));
for (const property of properties) {
const name = property.name === '_' ? ARGS_PROPERTY_NAME : property.name;
printed.push(
`\n${green(pad(name, longest_task_name))} `,
gray(pad(property.schema.type, longest_type)) + ' ',
pad(print_value(property.schema.default), longest_default) + ' ',
property.schema.description || '(no description available)',
);
}
if (!properties.length) {
printed.push('\n' + gray('this task has no args'));
}
}
log.info(...printed, '\n');
};
interface Arg_Schema_Property {
name: string;
schema: Arg_Schema;
}
const to_arg_properties = (def: ZodTypeDef, meta: Task_Module_Meta): Arg_Schema_Property[] => {
const type_name = to_type_name(def);
if (type_name !== ZodFirstPartyTypeKind.ZodObject) {
throw Error(
`Expected Args for task "${meta.name}" to be a ZodObject schema but got ${type_name}`,
);
}
const shape = (def as ZodObjectDef).shape();
const properties: Arg_Schema_Property[] = [];
for (const name in shape) {
if ('no-' + name in shape) continue;
const s = shape[name];
const schema: Arg_Schema = {
type: to_args_schema_type(s),
description: to_args_schema_description(s),
default: to_args_schema_default(s),
};
properties.push({name, schema});
}
return properties;
};
// quick n dirty padding logic
const pad = (s: string, n: number): string => s + ' '.repeat(n - s.length);
const to_max_length = <T>(items: T[], toString: (item: T) => string) =>
items.reduce((max, m) => Math.max(toString(m).length, max), 0);
// The following Zod helpers only need to support single-depth schemas for CLI args,
// but there's generic recursion to handle things like `ZodOptional` and `ZodDefault`.
const to_type_name = (def: ZodTypeDef): ZodFirstPartyTypeKind => (def as any).typeName;
const to_args_schema_type = ({_def}: ZodTypeAny): Arg_Schema['type'] => {
const t = to_type_name(_def);
switch (t) {
case ZodFirstPartyTypeKind.ZodBoolean:
return 'boolean';
case ZodFirstPartyTypeKind.ZodString:
return 'string';
case ZodFirstPartyTypeKind.ZodNumber:
return 'number';
case ZodFirstPartyTypeKind.ZodArray:
return 'string[]'; // TODO support arrays of arbitrary types, or more hardcoded ones as needed
case ZodFirstPartyTypeKind.ZodEnum:
return _def.values.map((v: string) => `'${v}'`).join(' | ');
case ZodFirstPartyTypeKind.ZodUnion:
return 'string | string[]'; // TODO support unions of arbitrary types, or more hardcoded ones as needed
default: {
if ('innerType' in _def) {
return to_args_schema_type(_def.innerType);
} else {
throw Error('Unknown zod type ' + t);
}
}
}
};
const to_args_schema_description = ({_def}: ZodTypeAny): string => {
if (_def.description) return _def.description;
if ('innerType' in _def) {
return to_args_schema_description(_def.innerType);
}
return '';
};
const to_args_schema_default = ({_def}: ZodTypeAny): any => {
if (_def.defaultValue) return _def.defaultValue();
if ('innerType' in _def) {
return to_args_schema_default(_def.innerType);
}
return undefined;
};