/
config.ts
245 lines (213 loc) · 6.78 KB
/
config.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { writeFileSync } from 'fs';
import { Command, Option } from '../models/command';
import {
getWorkspace,
getWorkspaceRaw,
migrateLegacyGlobalConfig,
validateWorkspace,
} from '../utilities/config';
import {
JsonValue,
JsonArray,
JsonObject,
JsonParseMode,
experimental,
parseJson,
tags,
} from '@angular-devkit/core';
const SilentError = require('silent-error');
export interface ConfigOptions {
jsonPath: string;
value?: string;
global?: boolean;
}
const validCliPaths = new Map([
['cli.warnings.versionMismatch', 'boolean'],
['cli.warnings.typescriptMismatch', 'boolean'],
['cli.defaultCollection', 'string'],
['cli.packageManager', 'string'],
]);
/**
* Splits a JSON path string into fragments. Fragments can be used to get the value referenced
* by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of
* ["a", 3, "foo", "bar", 2].
* @param path The JSON string to parse.
* @returns {string[]} The fragments for the string.
* @private
*/
function parseJsonPath(path: string): string[] {
const fragments = (path || '').split(/\./g);
const result: string[] = [];
while (fragments.length > 0) {
const fragment = fragments.shift();
const match = fragment.match(/([^\[]+)((\[.*\])*)/);
if (!match) {
throw new Error('Invalid JSON path.');
}
result.push(match[1]);
if (match[2]) {
const indices = match[2].slice(1, -1).split('][');
result.push(...indices);
}
}
return result.filter(fragment => !!fragment);
}
function getValueFromPath<T extends JsonArray | JsonObject>(
root: T,
path: string,
): JsonValue | undefined {
const fragments = parseJsonPath(path);
try {
return fragments.reduce((value: JsonValue, current: string | number) => {
if (value == undefined || typeof value != 'object') {
return undefined;
} else if (typeof current == 'string' && !Array.isArray(value)) {
return value[current];
} else if (typeof current == 'number' && Array.isArray(value)) {
return value[current];
} else {
return undefined;
}
}, root);
} catch {
return undefined;
}
}
function setValueFromPath<T extends JsonArray | JsonObject>(
root: T,
path: string,
newValue: JsonValue,
): JsonValue | undefined {
const fragments = parseJsonPath(path);
try {
return fragments.reduce((value: JsonValue, current: string | number, index: number) => {
if (value == undefined || typeof value != 'object') {
return undefined;
} else if (typeof current == 'string' && !Array.isArray(value)) {
if (index === fragments.length - 1) {
value[current] = newValue;
} else if (value[current] == undefined) {
if (typeof fragments[index + 1] == 'number') {
value[current] = [];
} else if (typeof fragments[index + 1] == 'string') {
value[current] = {};
}
}
return value[current];
} else if (typeof current == 'number' && Array.isArray(value)) {
if (index === fragments.length - 1) {
value[current] = newValue;
} else if (value[current] == undefined) {
if (typeof fragments[index + 1] == 'number') {
value[current] = [];
} else if (typeof fragments[index + 1] == 'string') {
value[current] = {};
}
}
return value[current];
} else {
return undefined;
}
}, root);
} catch {
return undefined;
}
}
function normalizeValue(value: string, path: string): JsonValue {
const cliOptionType = validCliPaths.get(path);
if (cliOptionType) {
switch (cliOptionType) {
case 'boolean':
if (value.trim() === 'true') {
return true;
} else if (value.trim() === 'false') {
return false;
}
break;
case 'number':
const numberValue = Number(value);
if (!Number.isNaN(numberValue)) {
return numberValue;
}
break;
case 'string':
return value;
}
throw new Error(`Invalid value type; expected a ${cliOptionType}.`);
}
return parseJson(value, JsonParseMode.Loose);
}
export default class ConfigCommand extends Command {
public readonly name = 'config';
public readonly description = 'Get/set configuration values.';
public readonly arguments = ['jsonPath', 'value'];
public readonly options: Option[] = [
{
name: 'global',
type: Boolean,
'default': false,
aliases: ['g'],
description: 'Get/set the value in the global configuration (in your home directory).'
}
];
public run(options: ConfigOptions) {
const level = options.global ? 'global' : 'local';
let config =
(getWorkspace(level) as {} as { _workspace: experimental.workspace.WorkspaceSchema });
if (options.global && !config) {
try {
if (migrateLegacyGlobalConfig()) {
config =
(getWorkspace(level) as {} as { _workspace: experimental.workspace.WorkspaceSchema });
this.logger.info(tags.oneLine`
We found a global configuration that was used in Angular CLI 1.
It has been automatically migrated.`);
}
} catch {}
}
if (options.value == undefined) {
if (!config) {
throw new SilentError('No config found.');
}
this.get(config._workspace, options);
} else {
this.set(options);
}
}
private get(config: experimental.workspace.WorkspaceSchema, options: ConfigOptions) {
const value = options.jsonPath ? getValueFromPath(config as any, options.jsonPath) : config;
if (value === undefined) {
throw new SilentError('Value cannot be found.');
} else if (typeof value == 'object') {
this.logger.info(JSON.stringify(value, null, 2));
} else {
this.logger.info(value.toString());
}
}
private set(options: ConfigOptions) {
if (!options.jsonPath || !options.jsonPath.trim()) {
throw new Error('Invalid Path.');
}
if (options.global
&& !options.jsonPath.startsWith('schematics.')
&& !validCliPaths.has(options.jsonPath)) {
throw new Error('Invalid Path.');
}
const [config, configPath] = getWorkspaceRaw(options.global ? 'global' : 'local');
// TODO: Modify & save without destroying comments
const configValue = config.value;
const value = normalizeValue(options.value, options.jsonPath);
const result = setValueFromPath(configValue, options.jsonPath, value);
if (result === undefined) {
throw new SilentError('Value cannot be found.');
}
try {
validateWorkspace(configValue);
} catch (error) {
this.logger.error(error.message);
throw new SilentError();
}
const output = JSON.stringify(configValue, null, 2);
writeFileSync(configPath, output);
}
}