Total Complexity | 8 |
Complexity/F | 8 |
Lines of Code | 45 |
Function Count | 1 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | type RegExpGroups<Groups extends string> = RegExpExecArray & {groups: Record<Groups, string>} |
||
2 | |||
3 | const parser = /^\s*([^\s=]+)=(?<quote>['"]?)(?<value>.*)(\k<quote>)/gm |
||
4 | , commentsStripper = /\s#.*/ |
||
5 | , exprParse = /\$\{([^\}]+?)(:-([^\}]*))?\}/g |
||
6 | |||
7 | export { |
||
8 | parse |
||
9 | } |
||
10 | |||
11 | function parse<K extends string>( |
||
12 | src: Buffer | string, |
||
13 | scope: undefined | Env, |
||
14 | reserved: undefined | Record<string, unknown> |
||
15 | ): Record<K, string> { |
||
16 | // TODO Line |
||
17 | // TODO Emit good error for bad `src` |
||
18 | const source = typeof src === "string" ? src : src.toString() |
||
19 | , $return = {} as Record<string, string> |
||
20 | , replacer = (_: string, variable: string, __: string, $default = "") => |
||
21 | scope && variable in scope ? scope[variable] ?? $default |
||
22 | : variable in $return ? $return[variable] |
||
23 | : $default |
||
24 | |||
25 | let parsed: ReturnType<RegExp["exec"]> |
||
26 | |||
27 | while (parsed = parser.exec(source)) { |
||
28 | const {1: key, "groups": { |
||
29 | value |
||
30 | }} = parsed as RegExpGroups<"value"|"quote"> |
||
31 | |||
32 | if ( |
||
33 | reserved && key in reserved |
||
34 | || scope && key in scope |
||
35 | ) |
||
36 | continue |
||
37 | |||
38 | $return[key] = value |
||
39 | .replace(commentsStripper, "") |
||
40 | .replace(exprParse, replacer) |
||
41 | } |
||
42 | |||
43 | return $return |
||
44 | } |
||
45 |