-
-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathconfig-service-impl.ts
375 lines (341 loc) · 12.2 KB
/
config-service-impl.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { promises as fs } from 'node:fs';
import { dirname } from 'node:path';
import yaml from 'js-yaml';
import { injectable, inject, named } from '@theia/core/shared/inversify';
import URI from '@theia/core/lib/common/uri';
import { ILogger } from '@theia/core/lib/common/logger';
import { FileUri } from '@theia/core/lib/node/file-uri';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { BackendApplicationContribution } from '@theia/core/lib/node/backend-application';
import {
ConfigService,
Config,
NotificationServiceServer,
Network,
ConfigState,
} from '../common/protocol';
import { spawnCommand } from './exec-util';
import { ArduinoDaemonImpl } from './arduino-daemon-impl';
import { DefaultCliConfig, CLI_CONFIG, CliConfig } from './cli-config';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { deepClone, nls } from '@theia/core';
import { ErrnoException } from './utils/errors';
import { createArduinoCoreServiceClient } from './arduino-core-service-client';
import {
ConfigurationSaveRequest,
SettingsSetValueRequest,
} from './cli-protocol/cc/arduino/cli/commands/v1/settings_pb';
const deepmerge = require('deepmerge');
@injectable()
export class ConfigServiceImpl
implements BackendApplicationContribution, ConfigService
{
@inject(ILogger)
@named('config')
private readonly logger: ILogger;
@inject(EnvVariablesServer)
private readonly envVariablesServer: EnvVariablesServer;
@inject(ArduinoDaemonImpl)
private readonly daemon: ArduinoDaemonImpl;
@inject(NotificationServiceServer)
private readonly notificationService: NotificationServiceServer;
private config: ConfigState = {
config: undefined,
messages: ['uninitialized'],
};
private cliConfig: DefaultCliConfig | undefined;
private ready = new Deferred<void>();
private readonly configChangeEmitter = new Emitter<{
oldState: ConfigState;
newState: ConfigState;
}>();
onStart(): void {
this.initConfig();
}
private async getCliConfigFileUri(): Promise<string> {
const configDirUri = await this.envVariablesServer.getConfigDirUri();
return new URI(configDirUri).resolve(CLI_CONFIG).toString();
}
async getConfiguration(): Promise<ConfigState> {
await this.ready.promise;
return { ...this.config };
}
// Used by frontend to update the config.
async setConfiguration(config: Config): Promise<void> {
await this.ready.promise;
if (Config.sameAs(this.config.config, config)) {
return;
}
const oldConfigState = deepClone(this.config);
let copyDefaultCliConfig: DefaultCliConfig | undefined = deepClone(
this.cliConfig
);
if (!copyDefaultCliConfig) {
copyDefaultCliConfig = await this.getFallbackCliConfig();
}
const { additionalUrls, dataDirUri, sketchDirUri, network, locale } =
config;
copyDefaultCliConfig.directories = {
data: FileUri.fsPath(dataDirUri),
user: FileUri.fsPath(sketchDirUri),
};
copyDefaultCliConfig.board_manager = {
additional_urls: [...additionalUrls],
};
copyDefaultCliConfig.locale = locale || 'en';
const proxy = Network.stringify(network);
copyDefaultCliConfig.network = proxy ? { proxy } : {}; // must be an empty object to unset the default prop with the `WriteRequest`.
// always use the port of the daemon
const port = await this.daemon.getPort();
await this.updateDaemon(port, copyDefaultCliConfig);
await this.writeDaemonState(port);
this.config.config = deepClone(config);
this.cliConfig = copyDefaultCliConfig;
try {
await this.validateCliConfig(this.cliConfig);
delete this.config.messages;
this.fireConfigChanged(oldConfigState, this.config);
} catch (err) {
if (err instanceof InvalidConfigError) {
this.config.messages = err.errors;
this.fireConfigChanged(oldConfigState, this.config);
} else {
throw err;
}
}
}
get cliConfiguration(): DefaultCliConfig | undefined {
return this.cliConfig;
}
get onConfigChange(): Event<{
oldState: ConfigState;
newState: ConfigState;
}> {
return this.configChangeEmitter.event;
}
private async initConfig(): Promise<void> {
this.logger.info('>>> Initializing CLI configuration...');
try {
const cliConfig = await this.loadCliConfig();
this.logger.info('Loaded the CLI configuration.');
this.cliConfig = cliConfig;
const [config] = await Promise.all([
this.mapCliConfigToAppConfig(this.cliConfig),
this.ensureUserDirExists(this.cliConfig).catch((reason) => {
if (reason instanceof Error) {
this.logger.warn(
`Could not ensure user directory existence: ${this.cliConfig?.directories.user}`,
reason
);
}
// NOOP. Try to create the folder if missing but swallow any errors.
// The validation will take care of the missing location handling.
}),
]);
this.config.config = config;
this.logger.info(
`Mapped the CLI configuration: ${JSON.stringify(this.config.config)}`
);
this.logger.info('Validating the CLI configuration...');
await this.validateCliConfig(this.cliConfig);
delete this.config.messages;
this.logger.info('The CLI config is valid.');
if (config) {
this.ready.resolve();
this.logger.info('<<< Initialized the CLI configuration.');
return;
}
} catch (err: unknown) {
this.logger.error('Failed to initialize the CLI configuration.', err);
if (err instanceof InvalidConfigError) {
this.config.messages = err.errors;
this.ready.resolve();
}
}
}
private async loadCliConfig(
initializeIfAbsent = true
): Promise<DefaultCliConfig> {
const cliConfigFileUri = await this.getCliConfigFileUri();
const cliConfigPath = FileUri.fsPath(cliConfigFileUri);
this.logger.info(`Loading CLI configuration from ${cliConfigPath}...`);
try {
const content = await fs.readFile(cliConfigPath, {
encoding: 'utf8',
});
const model = (yaml.safeLoad(content) || {}) as CliConfig;
this.logger.info(`Loaded CLI configuration: ${JSON.stringify(model)}`);
if (model.directories?.data && model.directories?.user) {
this.logger.info(
"'directories.data' and 'directories.user' are set in the CLI configuration model."
);
return model as DefaultCliConfig;
}
// The CLI can run with partial (missing `port`, `directories`), the IDE2 cannot.
// We merge the default CLI config with the partial user's config.
this.logger.info(
"Loading fallback CLI configuration to get 'directories.data' and 'directories.user'"
);
const fallbackModel = await this.getFallbackCliConfig();
this.logger.info(
`Loaded fallback CLI configuration: ${JSON.stringify(fallbackModel)}`
);
const mergedModel = deepmerge(fallbackModel, model) as DefaultCliConfig;
this.logger.info(
`Merged CLI configuration with the fallback: ${JSON.stringify(
mergedModel
)}`
);
return mergedModel;
} catch (error) {
if (ErrnoException.isENOENT(error)) {
if (initializeIfAbsent) {
await this.initCliConfigTo(dirname(cliConfigPath));
return this.loadCliConfig(false);
}
}
throw error;
}
}
private async getFallbackCliConfig(): Promise<DefaultCliConfig> {
const cliPath = this.daemon.getExecPath();
const [configRaw, directoriesRaw] = await Promise.all([
spawnCommand(cliPath, ['config', 'dump', '--json']),
// Since CLI 1.0, the command `config dump` only returns user-modified values and not default ones.
// directories.user and directories.data are required by IDE2 so we get the default value explicitly.
spawnCommand(cliPath, ['config', 'get', 'directories', '--json']),
]);
const config = JSON.parse(configRaw);
const { user, data } = JSON.parse(directoriesRaw);
return { ...config.config, directories: { user, data } };
}
private async initCliConfigTo(fsPathToDir: string): Promise<void> {
const cliPath = this.daemon.getExecPath();
await spawnCommand(cliPath, ['config', 'init', '--dest-dir', fsPathToDir]);
}
private async mapCliConfigToAppConfig(
cliConfig: DefaultCliConfig
): Promise<Config> {
const { directories, locale = 'en' } = cliConfig;
const { user, data } = directories;
const additionalUrls: Array<string> = [];
if (cliConfig.board_manager && cliConfig.board_manager.additional_urls) {
additionalUrls.push(
...Array.from(new Set(cliConfig.board_manager.additional_urls))
);
}
const network = Network.parse(cliConfig.network?.proxy);
return {
dataDirUri: FileUri.create(data).toString(),
sketchDirUri: FileUri.create(user).toString(),
additionalUrls,
network,
locale,
};
}
private fireConfigChanged(
oldState: ConfigState,
newState: ConfigState
): void {
this.configChangeEmitter.fire({ oldState, newState });
this.notificationService.notifyConfigDidChange(newState);
}
private async validateCliConfig(config: DefaultCliConfig): Promise<void> {
const errors: string[] = [];
errors.push(...(await this.checkAccessible(config)));
if (errors.length) {
throw new InvalidConfigError(errors);
}
}
private async checkAccessible({
directories,
}: DefaultCliConfig): Promise<string[]> {
try {
await fs.readdir(directories.user);
return [];
} catch (err) {
console.error(
`Check accessible failed for input: ${directories.user}`,
err
);
return [
nls.localize(
'arduino/configuration/cli/inaccessibleDirectory',
"Could not access the sketchbook location at '{0}': {1}",
directories.user,
String(err)
),
];
}
}
private async updateDaemon(
port: number,
config: DefaultCliConfig
): Promise<void> {
const json = JSON.stringify(config, null, 2);
this.logger.info(`Updating daemon with 'data': ${json}`);
const updatableConfig = {
locale: config.locale,
'directories.user': config.directories.user,
'directories.data': config.directories.data,
'network.proxy': config.network?.proxy,
'board_manager.additional_urls':
config.board_manager?.additional_urls || [],
};
const client = createArduinoCoreServiceClient({ port });
for (const [key, value] of Object.entries(updatableConfig)) {
const req = new SettingsSetValueRequest();
req.setKey(key);
req.setEncodedValue(JSON.stringify(value));
await new Promise<void>((resolve) => {
client.settingsSetValue(req, (error) => {
if (error) {
this.logger.error(
`Could not update config with key: ${key} and value: ${value}`,
error
);
}
resolve();
});
});
}
client.close();
}
private async writeDaemonState(port: number): Promise<void> {
const client = createArduinoCoreServiceClient({ port });
const req = new ConfigurationSaveRequest();
req.setSettingsFormat('yaml');
const configRaw = await new Promise<string>((resolve, reject) => {
client.configurationSave(req, (error, resp) => {
try {
if (error) {
reject(error);
return;
}
resolve(resp.getEncodedSettings());
} finally {
client.close();
}
});
});
const cliConfigUri = await this.getCliConfigFileUri();
const cliConfigPath = FileUri.fsPath(cliConfigUri);
await fs.writeFile(cliConfigPath, configRaw, { encoding: 'utf-8' });
}
// #1445
private async ensureUserDirExists(
cliConfig: DefaultCliConfig
): Promise<void> {
await fs.mkdir(cliConfig.directories.user, { recursive: true });
}
}
class InvalidConfigError extends Error {
constructor(readonly errors: string[]) {
super('InvalidConfigError:\n - ' + errors.join('\n - '));
if (!errors.length) {
throw new Error("Illegal argument: 'messages'. It must not be empty.");
}
Object.setPrototypeOf(this, InvalidConfigError.prototype);
}
}