-
-
Notifications
You must be signed in to change notification settings - Fork 431
/
Copy pathconfig-service-impl.ts
301 lines (275 loc) · 9.32 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
import * as fs from 'fs';
import * as path from 'path';
import * as temp from 'temp';
import * as yaml from 'js-yaml';
import { promisify } from 'util';
import * as grpc from '@grpc/grpc-js';
import { injectable, inject, named } from '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,
} from '../common/protocol';
import { spawnCommand } from './exec-util';
import {
MergeRequest,
WriteRequest,
} from './cli-protocol/cc/arduino/cli/settings/v1/settings_pb';
import { SettingsServiceClient } from './cli-protocol/cc/arduino/cli/settings/v1/settings_grpc_pb';
import * as serviceGrpcPb from './cli-protocol/cc/arduino/cli/settings/v1/settings_grpc_pb';
import { ArduinoDaemonImpl } from './arduino-daemon-impl';
import { DefaultCliConfig, CLI_CONFIG } from './cli-config';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { deepClone } from '@theia/core';
const deepmerge = require('deepmerge');
const track = temp.track();
@injectable()
export class ConfigServiceImpl
implements BackendApplicationContribution, ConfigService
{
@inject(ILogger)
@named('config')
protected readonly logger: ILogger;
@inject(EnvVariablesServer)
protected readonly envVariablesServer: EnvVariablesServer;
@inject(ArduinoDaemonImpl)
protected readonly daemon: ArduinoDaemonImpl;
@inject(NotificationServiceServer)
protected readonly notificationService: NotificationServiceServer;
protected config: Config;
protected cliConfig: DefaultCliConfig | undefined;
protected ready = new Deferred<void>();
protected readonly configChangeEmitter = new Emitter<Config>();
async onStart(): Promise<void> {
await this.ensureCliConfigExists();
this.cliConfig = await this.loadCliConfig();
if (this.cliConfig) {
const config = await this.mapCliConfigToAppConfig(this.cliConfig);
if (config) {
this.config = config;
this.ready.resolve();
return;
}
}
this.fireInvalidConfig();
}
async getCliConfigFileUri(): Promise<string> {
const configDirUri = await this.envVariablesServer.getConfigDirUri();
return new URI(configDirUri).resolve(CLI_CONFIG).toString();
}
async getConfiguration(): Promise<Config> {
await this.ready.promise;
return this.config;
}
async setConfiguration(config: Config): Promise<void> {
await this.ready.promise;
if (Config.sameAs(this.config, config)) {
return;
}
let copyDefaultCliConfig: DefaultCliConfig | undefined = deepClone(
this.cliConfig
);
if (!copyDefaultCliConfig) {
copyDefaultCliConfig = await this.getFallbackCliConfig();
}
const {
additionalUrls,
dataDirUri,
downloadsDirUri,
sketchDirUri,
network,
} = config;
copyDefaultCliConfig.directories = {
data: FileUri.fsPath(dataDirUri),
downloads: FileUri.fsPath(downloadsDirUri),
user: FileUri.fsPath(sketchDirUri),
};
copyDefaultCliConfig.board_manager = {
additional_urls: [...additionalUrls],
};
const proxy = Network.stringify(network);
copyDefaultCliConfig.network = { proxy };
const { port } = copyDefaultCliConfig.daemon;
await this.updateDaemon(port, copyDefaultCliConfig);
await this.writeDaemonState(port);
this.config = deepClone(config);
this.cliConfig = copyDefaultCliConfig;
this.fireConfigChanged(this.config);
}
get cliConfiguration(): DefaultCliConfig | undefined {
return this.cliConfig;
}
get onConfigChange(): Event<Config> {
return this.configChangeEmitter.event;
}
async getVersion(): Promise<
Readonly<{ version: string; commit: string; status?: string }>
> {
return this.daemon.getVersion();
}
async isInDataDir(uri: string): Promise<boolean> {
return this.getConfiguration().then(({ dataDirUri }) =>
new URI(dataDirUri).isEqualOrParent(new URI(uri))
);
}
async isInSketchDir(uri: string): Promise<boolean> {
return this.getConfiguration().then(({ sketchDirUri }) =>
new URI(sketchDirUri).isEqualOrParent(new URI(uri))
);
}
protected async loadCliConfig(): Promise<DefaultCliConfig | undefined> {
const cliConfigFileUri = await this.getCliConfigFileUri();
const cliConfigPath = FileUri.fsPath(cliConfigFileUri);
try {
const content = await promisify(fs.readFile)(cliConfigPath, {
encoding: 'utf8',
});
const model = yaml.safeLoad(content) || {};
// The CLI can run with partial (missing `port`, `directories`), the app cannot, we merge the default with the user's config.
const fallbackModel = await this.getFallbackCliConfig();
return deepmerge(fallbackModel, model) as DefaultCliConfig;
} catch (error) {
this.logger.error(
`Error occurred when loading CLI config from ${cliConfigPath}.`,
error
);
}
return undefined;
}
protected async getFallbackCliConfig(): Promise<DefaultCliConfig> {
const cliPath = await this.daemon.getExecPath();
const throwawayDirPath = await new Promise<string>((resolve, reject) => {
track.mkdir({}, (err, dirPath) => {
if (err) {
reject(err);
return;
}
resolve(dirPath);
});
});
await spawnCommand(`"${cliPath}"`, [
'config',
'init',
'--dest-dir',
`"${throwawayDirPath}"`,
]);
const rawYaml = await promisify(fs.readFile)(
path.join(throwawayDirPath, CLI_CONFIG),
{ encoding: 'utf-8' }
);
const model = yaml.safeLoad(rawYaml.trim());
return model as DefaultCliConfig;
}
protected async ensureCliConfigExists(): Promise<void> {
const cliConfigFileUri = await this.getCliConfigFileUri();
const cliConfigPath = FileUri.fsPath(cliConfigFileUri);
let exists = await promisify(fs.exists)(cliConfigPath);
if (!exists) {
await this.initCliConfigTo(path.dirname(cliConfigPath));
exists = await promisify(fs.exists)(cliConfigPath);
if (!exists) {
throw new Error(
`Could not initialize the default CLI configuration file at ${cliConfigPath}.`
);
}
}
}
protected async initCliConfigTo(fsPathToDir: string): Promise<void> {
const cliPath = await this.daemon.getExecPath();
await spawnCommand(`"${cliPath}"`, [
'config',
'init',
'--dest-dir',
`"${fsPathToDir}"`,
]);
}
protected async mapCliConfigToAppConfig(
cliConfig: DefaultCliConfig
): Promise<Config> {
const { directories } = cliConfig;
const { data, user, downloads } = 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(),
downloadsDirUri: FileUri.create(downloads).toString(),
additionalUrls,
network,
};
}
protected fireConfigChanged(config: Config): void {
this.configChangeEmitter.fire(config);
this.notificationService.notifyConfigChanged({ config });
}
protected fireInvalidConfig(): void {
this.notificationService.notifyConfigChanged({ config: undefined });
}
protected async updateDaemon(
port: string | number,
config: DefaultCliConfig
): Promise<void> {
const client = this.createClient(port);
const req = new MergeRequest();
const json = JSON.stringify(config, null, 2);
req.setJsonData(json);
console.log(`Updating daemon with 'data': ${json}`);
return new Promise<void>((resolve, reject) => {
client.merge(req, (error) => {
try {
if (error) {
reject(error);
return;
}
resolve();
} finally {
client.close();
}
});
});
}
protected async writeDaemonState(port: string | number): Promise<void> {
const client = this.createClient(port);
const req = new WriteRequest();
const cliConfigUri = await this.getCliConfigFileUri();
const cliConfigPath = FileUri.fsPath(cliConfigUri);
req.setFilePath(cliConfigPath);
return new Promise<void>((resolve, reject) => {
client.write(req, (error) => {
try {
if (error) {
reject(error);
return;
}
resolve();
} finally {
client.close();
}
});
});
}
private createClient(port: string | number): SettingsServiceClient {
// https://github.com/agreatfool/grpc_tools_node_protoc_ts/blob/master/doc/grpcjs_support.md#usage
const SettingsServiceClient = grpc.makeClientConstructor(
// @ts-expect-error: ignore
serviceGrpcPb['cc.arduino.cli.settings.v1.SettingsService'],
'SettingsServiceService'
) as any;
return new SettingsServiceClient(
`localhost:${port}`,
grpc.credentials.createInsecure()
) as SettingsServiceClient;
}
}