forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject-config-service.ts
520 lines (461 loc) · 13.8 KB
/
project-config-service.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
import * as constants from "../constants";
import {
CONFIG_FILE_NAME_DISPLAY,
CONFIG_FILE_NAME_JS,
CONFIG_FILE_NAME_TS,
CONFIG_NS_FILE_NAME,
} from "../constants";
import * as path from "path";
import * as _ from "lodash";
import * as ts from "typescript";
import { IFileSystem, IProjectHelper } from "../common/declarations";
import {
INsConfig,
IProjectConfigInformation,
IProjectConfigService,
} from "../definitions/project";
import { IInjector } from "../common/definitions/yok";
import {
ConfigTransformer,
IConfigTransformer,
SupportedConfigValues,
} from "../tools/config-manipulation/config-transformer";
import { IBasePluginData } from "../definitions/plugins";
import { injector } from "../common/yok";
import { EOL } from "os";
import {
format as prettierFormat,
resolveConfig as resolvePrettierConfig,
} from "prettier";
import { cache, exported } from "../common/decorators";
import { IOptions } from "../declarations";
import semver = require("semver/preload");
import { ICleanupService } from "../definitions/cleanup-service";
export class ProjectConfigService implements IProjectConfigService {
private forceUsingNewConfig: boolean = false;
private forceUsingLegacyConfig: boolean = false;
constructor(
private $fs: IFileSystem,
private $logger: ILogger,
private $injector: IInjector,
private $options: IOptions,
private $cleanupService: ICleanupService
) {}
public setForceUsingNewConfig(force: boolean) {
return (this.forceUsingNewConfig = force);
}
public setForceUsingLegacyConfig(force: boolean) {
return (this.forceUsingLegacyConfig = force);
}
private requireFromString(src: string, filename: string): NodeModule {
// @ts-ignore
const m = new module.constructor();
m.paths = module.paths;
m._compile(src, filename);
return m.exports;
}
get projectHelper(): IProjectHelper {
return this.$injector.resolve("projectHelper");
}
public getDefaultTSConfig(
appId: string = "org.nativescript.app",
appPath: string = "app"
) {
return `import { NativeScriptConfig } from '@nativescript/core';
export default {
id: '${appId}',
appPath: '${appPath}',
appResourcesPath: 'App_Resources',
android: {
v8Flags: '--expose_gc',
markingMode: 'none'
}
} as NativeScriptConfig;`.trim();
}
@cache() // @cache should prevent the message being printed multiple times
private warnUsingLegacyNSConfig() {
// todo: remove hack
const isMigrate = _.get(this.$options, "argv._[0]") === "migrate";
if (isMigrate) {
return;
}
this.$logger.warn(
`You are using the deprecated ${CONFIG_NS_FILE_NAME} file. Just be aware that NativeScript now has an improved ${CONFIG_FILE_NAME_DISPLAY} file for when you're ready to upgrade this project.`
);
}
private getConfigPathsFromPossiblePaths(paths: {
[key: string]: string[];
}): any {
const {
possibleTSConfigPaths,
possibleJSConfigPaths,
possibleNSConfigPaths,
} = paths;
let TSConfigPath;
let JSConfigPath;
let NSConfigPath;
// look up a ts config first
TSConfigPath = possibleTSConfigPaths
.filter(Boolean)
.find((path) => this.$fs.exists(path));
// if not found, look up a JS config
if (!TSConfigPath) {
JSConfigPath = possibleJSConfigPaths
.filter(Boolean)
.find((path) => this.$fs.exists(path));
}
// lastly look for nsconfig/json config
if (!TSConfigPath && !JSConfigPath) {
NSConfigPath = possibleNSConfigPaths
.filter(Boolean)
.find((path) => this.$fs.exists(path));
}
return {
TSConfigPath,
JSConfigPath,
NSConfigPath,
found: TSConfigPath || JSConfigPath || NSConfigPath,
};
}
public detectProjectConfigs(projectDir?: string): IProjectConfigInformation {
const possibleTSConfigPaths = [];
const possibleJSConfigPaths = [];
const possibleNSConfigPaths = [];
let paths;
// allow overriding config name with env variable or --config (or -c)
const configFilename =
process.env.NATIVESCRIPT_CONFIG_NAME ?? this.$options.config;
if (configFilename) {
const fullPath = this.$fs.isRelativePath(configFilename)
? path.join(projectDir || this.projectHelper.projectDir, configFilename)
: configFilename;
possibleTSConfigPaths.unshift(
fullPath.endsWith(".ts") ? fullPath : `${fullPath}.ts`
);
possibleJSConfigPaths.unshift(
fullPath.endsWith(".js") ? fullPath : `${fullPath}.js`
);
possibleNSConfigPaths.unshift(
fullPath.endsWith(".json") ? fullPath : `${fullPath}.json`
);
paths = this.getConfigPathsFromPossiblePaths({
possibleTSConfigPaths,
possibleJSConfigPaths,
possibleNSConfigPaths,
});
}
// look up default paths if no path found yet
if (!paths?.found) {
possibleTSConfigPaths.push(
path.join(
projectDir || this.projectHelper.projectDir,
CONFIG_FILE_NAME_TS
)
);
possibleJSConfigPaths.push(
path.join(
projectDir || this.projectHelper.projectDir,
CONFIG_FILE_NAME_JS
)
);
possibleNSConfigPaths.push(
path.join(
projectDir || this.projectHelper.projectDir,
CONFIG_NS_FILE_NAME
)
);
paths = this.getConfigPathsFromPossiblePaths({
possibleTSConfigPaths,
possibleJSConfigPaths,
possibleNSConfigPaths,
});
}
const hasTSConfig = !!paths.TSConfigPath;
const hasJSConfig = !!paths.JSConfigPath;
const hasNSConfig = !!paths.NSConfigPath;
const usingNSConfig = !(hasTSConfig || hasJSConfig);
if (hasTSConfig && hasJSConfig) {
this.$logger.warn(
`You have both a ${CONFIG_FILE_NAME_JS} and ${CONFIG_FILE_NAME_TS} file. Defaulting to ${CONFIG_FILE_NAME_TS}.`
);
}
return {
hasTSConfig,
hasJSConfig,
hasNSConfig,
usingNSConfig,
TSConfigPath: paths.TSConfigPath,
JSConfigPath: paths.JSConfigPath,
NSConfigPath: paths.NSConfigPath,
};
}
@exported("projectConfigService")
public readConfig(projectDir?: string): INsConfig {
const info = this.detectProjectConfigs(projectDir);
if (
this.forceUsingLegacyConfig ||
(info.usingNSConfig && !this.forceUsingNewConfig)
) {
this.$logger.trace(
"Project Config Service using legacy configuration..."
);
if (!this.forceUsingLegacyConfig && info.hasNSConfig) {
this.warnUsingLegacyNSConfig();
}
return this.fallbackToLegacyNSConfig(info);
}
let config: INsConfig;
if (info.hasTSConfig) {
const rawSource = this.$fs.readText(info.TSConfigPath);
const transpiledSource = ts.transpileModule(rawSource, {
compilerOptions: { module: ts.ModuleKind.CommonJS },
});
const result: any = this.requireFromString(
transpiledSource.outputText,
info.TSConfigPath
);
config = result["default"] ? result["default"] : result;
} else if (info.hasJSConfig) {
const rawSource = this.$fs.readText(info.JSConfigPath);
config = this.requireFromString(rawSource, info.JSConfigPath);
}
return config;
}
@exported("projectConfigService")
public getValue(key: string, defaultValue?: any): any {
return _.get(this.readConfig(), key, defaultValue);
}
@exported("projectConfigService")
public async setValue(
key: string,
value: SupportedConfigValues
): Promise<boolean> {
const {
hasTSConfig,
hasNSConfig,
TSConfigPath,
JSConfigPath,
usingNSConfig,
NSConfigPath,
} = this.detectProjectConfigs();
const configFilePath = TSConfigPath || JSConfigPath;
if (
this.forceUsingLegacyConfig ||
(usingNSConfig && !this.forceUsingNewConfig)
) {
try {
this.$logger.trace(
"Project Config Service -> setValue writing to legacy config."
);
const NSConfig = hasNSConfig ? this.$fs.readJson(NSConfigPath) : {};
_.set(NSConfig, key, value);
this.$fs.writeJson(NSConfigPath, NSConfig);
return true;
} catch (error) {
this.$logger.trace(
`Failed to setValue on legacy config. Error is ${error.message}`,
error
);
return false;
}
}
if (!this.$fs.exists(configFilePath)) {
this.writeDefaultConfig(this.projectHelper.projectDir);
}
if (typeof value === "object") {
let allSuccessful = true;
for (const prop of this.flattenObjectToPaths(value)) {
if (!(await this.setValue(prop.key, prop.value))) {
allSuccessful = false;
}
}
return allSuccessful;
}
const configContent = this.$fs.readText(configFilePath);
try {
const transformer: IConfigTransformer = new ConfigTransformer(
configContent
);
const newContent = transformer.setValue(key, value);
const prettierOptions = (await resolvePrettierConfig(
this.projectHelper.projectDir,
{ editorconfig: true }
)) || {
semi: false,
singleQuote: true,
};
this.$logger.trace(
"updating config, prettier options: ",
prettierOptions
);
this.$fs.writeFile(
configFilePath,
prettierFormat(newContent, {
...prettierOptions,
parser: "typescript",
})
);
} catch (error) {
this.$logger.error(`Failed to update config.` + error);
} finally {
// verify config is updated correctly
if (this.getValue(key) !== value) {
this.$logger.error(
`${EOL}Failed to update ${
hasTSConfig ? CONFIG_FILE_NAME_TS : CONFIG_FILE_NAME_JS
}.${EOL}`
);
this.$logger.printMarkdown(
`Please manually update \`${
hasTSConfig ? CONFIG_FILE_NAME_TS : CONFIG_FILE_NAME_JS
}\` and set \`${key}\` to \`${value}\`.${EOL}`
);
// restore original content
this.$fs.writeFile(configFilePath, configContent);
return false;
}
return true;
}
}
public writeDefaultConfig(projectDir: string, appId?: string) {
const { TSConfigPath } = this.detectProjectConfigs(projectDir);
if (this.$fs.exists(TSConfigPath)) {
return false;
}
const possibleAppPaths = [
path.resolve(projectDir, constants.SRC_DIR),
path.resolve(projectDir, constants.APP_FOLDER_NAME),
];
let appPath = possibleAppPaths.find((possiblePath) =>
this.$fs.exists(possiblePath)
);
if (appPath) {
appPath = path.relative(projectDir, appPath).replace(path.sep, "/");
}
this.$fs.writeFile(TSConfigPath, this.getDefaultTSConfig(appId, appPath));
return TSConfigPath;
}
private fallbackToLegacyNSConfig(info: IProjectConfigInformation) {
const additionalData: Array<object> = [];
const NSConfig: any = info.hasNSConfig
? this.$fs.readJson(info.NSConfigPath)
: {};
try {
// injecting here to avoid circular dependency
const projectData = this.$injector.resolve("projectData");
const embeddedPackageJsonPath = path.resolve(
this.projectHelper.projectDir,
projectData.getAppDirectoryRelativePath(),
constants.PACKAGE_JSON_FILE_NAME
);
const embeddedPackageJson = this.$fs.readJson(embeddedPackageJsonPath);
// filter only the supported keys
additionalData.push(
_.pick(embeddedPackageJson, [
"android",
"ios",
"profiling",
"cssParser",
"discardUncaughtJsExceptions",
"main",
])
);
} catch (err) {
this.$logger.trace(
"failed to add embedded package.json data to config",
err
);
// ignore if the file doesn't exist
}
try {
const packageJson = this.$fs.readJson(
path.join(this.projectHelper.projectDir, "package.json")
);
// add app id to additionalData for backwards compatibility
if (
!NSConfig.id &&
packageJson &&
packageJson.nativescript &&
packageJson.nativescript.id
) {
const ids = packageJson.nativescript.id;
if (typeof ids === "string") {
additionalData.push({
id: packageJson.nativescript.id,
});
} else if (typeof ids === "object") {
for (const platform of Object.keys(ids)) {
additionalData.push({
[platform]: {
id: packageJson.nativescript.id[platform],
},
});
}
}
}
} catch (err) {
this.$logger.trace("failed to read package.json data for config", err);
// ignore if the file doesn't exist
}
return _.defaultsDeep({}, ...additionalData, NSConfig);
// return Object.assign({}, ...additionalData, NSConfig);
}
public async writeLegacyNSConfigIfNeeded(
projectDir: string,
runtimePackage: IBasePluginData
) {
const { usingNSConfig } = this.detectProjectConfigs(projectDir);
if (usingNSConfig) {
return;
}
if (
runtimePackage.version &&
semver.gte(semver.coerce(runtimePackage.version), "7.0.0-rc.5")
) {
// runtimes >= 7.0.0-rc.5 support passing appPath and appResourcesPath through gradle project flags
// so writing an nsconfig is not necessary.
return;
}
const runtimePackageDisplay = `${runtimePackage.name}${
runtimePackage.version ? " v" + runtimePackage.version : ""
}`;
this.$logger.info();
this.$logger.printMarkdown(`
Using __${runtimePackageDisplay}__ which requires \`nsconfig.json\` to be present.
Writing \`nsconfig.json\` based on the values set in \`${CONFIG_FILE_NAME_DISPLAY}\`.
You may add \`nsconfig.json\` to \`.gitignore\` as the CLI will regenerate it as necessary.`);
const nsConfigPath = path.join(
projectDir || this.projectHelper.projectDir,
"nsconfig.json"
);
this.$fs.writeJson(nsConfigPath, {
_info1: `Auto Generated for backwards compatibility with the currently used runtime.`,
_info2: `Do not edit this file manually, as any changes will be ignored.`,
_info3: `Config changes should be done in ${CONFIG_FILE_NAME_DISPLAY} instead.`,
appPath: this.getValue("appPath"),
appResourcesPath: this.getValue("appResourcesPath"),
});
// mark the file for cleanup after the CLI exits
await this.$cleanupService.addCleanupDeleteAction(nsConfigPath);
}
// todo: move into config manipulation
private flattenObjectToPaths(
obj: any,
basePath?: string
): Array<{ key: string; value: any }> {
const toPath = (key: any) => [basePath, key].filter(Boolean).join(".");
return Object.keys(obj).reduce((all: any, key) => {
if (typeof obj[key] === "object") {
return [...all, ...this.flattenObjectToPaths(obj[key], toPath(key))];
}
return [
...all,
{
key: toPath(key),
value: obj[key],
},
];
}, []);
}
}
injector.register("projectConfigService", ProjectConfigService);