-
Notifications
You must be signed in to change notification settings - Fork 4
/
duration.ts
82 lines (73 loc) · 2.67 KB
/
duration.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
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { Flags } from '@oclif/core';
import { Messages } from '@salesforce/core/messages';
import { Duration } from '@salesforce/kit';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/sf-plugins-core', 'messages');
type DurationUnit = Lowercase<keyof typeof Duration.Unit>;
export type DurationFlagConfig = {
unit: Required<DurationUnit>;
defaultValue?: number;
min?: number;
max?: number;
};
/**
* Duration flag with built-in default and min/max validation
* You must specify a unit
* Defaults to undefined if you don't specify a default
*
* @example
*
* ```
* import { Flags } from '@salesforce/sf-plugins-core';
* public static flags = {
* wait: Flags.duration({
* min: 1,
* unit: 'minutes'
* defaultValue: 33,
* char: 'w',
* description: 'Wait time in minutes'
* }),
* }
* ```
*/
export const durationFlag = Flags.custom<Duration, DurationFlagConfig>({
// eslint-disable-next-line @typescript-eslint/require-await
parse: async (input, _, opts) => validate(input, opts),
// eslint-disable-next-line @typescript-eslint/require-await
default: async (context) =>
typeof context.options.defaultValue === 'number'
? toDuration(context.options.defaultValue, context.options.unit)
: undefined,
// eslint-disable-next-line @typescript-eslint/require-await
defaultHelp: async (context) =>
typeof context.options.defaultValue === 'number'
? toDuration(context.options.defaultValue, context.options.unit).toString()
: undefined,
});
const validate = (input: string, config: DurationFlagConfig): Duration => {
const { min, max, unit } = config || {};
let parsedInput: number;
try {
parsedInput = parseInt(input, 10);
if (typeof parsedInput !== 'number' || isNaN(parsedInput)) {
throw messages.createError('errors.InvalidDuration');
}
} catch (e) {
throw messages.createError('errors.InvalidDuration');
}
if (min && max && (parsedInput < min || parsedInput > max)) {
throw messages.createError('errors.DurationBounds', [min, max]);
} else if (min && parsedInput < min) {
throw messages.createError('errors.DurationBoundsMin', [min]);
} else if (max && parsedInput > max) {
throw messages.createError('errors.DurationBoundsMax', [max]);
}
return toDuration(parsedInput, unit);
};
const toDuration = (parsedInput: number, unit: DurationUnit): Duration => Duration[unit](parsedInput);