-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcodegenWindows.ts
More file actions
342 lines (310 loc) · 9.74 KB
/
Copy pathcodegenWindows.ts
File metadata and controls
342 lines (310 loc) · 9.74 KB
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
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
* @format
*/
import path from 'path';
import chalk from 'chalk';
import {performance} from 'perf_hooks';
import {Ora} from 'ora';
import type {Command, Config} from '@react-native-community/cli-types';
import {Telemetry, CodedError} from '@react-native-windows/telemetry';
import type {
CodeGenOptions as RnwCodeGenOptions,
CppStringTypes,
} from '@react-native-windows/codegen';
import {runCodeGen} from '@react-native-windows/codegen';
import {
newSpinner,
setExitProcessWithError,
} from '../../utils/commandWithProgress';
import {
getDefaultOptions,
startTelemetrySession,
endTelemetrySession,
} from '../../utils/telemetryHelpers';
import type {CodeGenOptions} from './codegenWindowsOptions';
import {codegenOptions} from './codegenWindowsOptions';
export class CodeGenWindows {
private changesNecessary: boolean;
public areChangesNeeded() {
return this.changesNecessary;
}
constructor(readonly root: string, readonly options: CodeGenOptions) {
this.changesNecessary = false;
}
public async run(spinner: Ora) {
const verbose = this.options.logging;
verboseMessage('', verbose);
verboseMessage('Loading codegenConfig from package.json');
const pkgJson = require(path.join(this.root, 'package.json'));
if (!pkgJson.codegenConfig) {
spinner.info(
`No ${chalk.bold(
'codegenConfig',
)} specified in package.json - ${chalk.yellow(
'Skipping codegen-windows',
)}`,
);
return;
}
const codegenConfigType = pkgJson.codegenConfig.type;
if (codegenConfigType !== 'modules' && codegenConfigType !== 'all') {
spinner.info(
`${chalk.bold(
'codegenConfig.type',
)} in package.json is not ${chalk.bold('modules')} or ${chalk.bold(
'all',
)} - ${chalk.yellow('Skipping codegen-windows')}`,
);
return;
}
if (!pkgJson.codegenConfig.windows) {
spinner.info(
`No ${chalk.bold(
'codegenConfig.windows',
)} specified in package.json - ${chalk.yellow(
'Skipping codegen-windows',
)}`,
);
return;
}
if (!pkgJson.codegenConfig.windows.namespace) {
throw new CodedError(
'InvalidCodegenConfig',
`Missing ${chalk.bold(
'codegenConfig.windows.namespace',
)} value in package.json`,
);
}
let cppStringType: CppStringTypes = 'std::string';
if (pkgJson.codegenConfig.windows.cppStringType) {
switch (pkgJson.codegenConfig.windows.cppStringType) {
case 'std::string':
case 'std::wstring':
cppStringType = pkgJson.codegenConfig.windows.cppStringType;
break;
default:
throw new CodedError(
'InvalidCodegenConfig',
`Value of ${chalk.bold(
'codegenConfig.windows.cppStringType',
)} in package.json should be either 'std::string' or 'std::wstring'`,
);
}
}
let separateDataTypes = false;
if (pkgJson.codegenConfig.windows.separateDataTypes !== undefined) {
switch (pkgJson.codegenConfig.windows.separateDataTypes) {
case true:
case false:
separateDataTypes = pkgJson.codegenConfig.windows.separateDataTypes;
break;
default:
throw new CodedError(
'InvalidCodegenConfig',
`Value of ${chalk.bold(
'codegenConfig.windows.separateDataTypes',
)} in package.json should be either true or false`,
);
}
}
if (!pkgJson.codegenConfig.name) {
throw new CodedError(
'InvalidCodegenConfig',
`Missing ${chalk.bold('codegenConfig.name')} value in package.json`,
);
}
const projectName = pkgJson.codegenConfig.name.replace(/[^a-zA-Z]/g, '');
const projectNamespace = pkgJson.codegenConfig.windows.namespace;
const jsRootDir = pkgJson.codegenConfig.jsSrcsDir
? path.join(this.root, pkgJson.codegenConfig.jsSrcsDir)
: this.root;
const codegenOutputDir =
pkgJson.codegenConfig.windows.outputDirectory ?? 'codegen';
const generators = pkgJson.codegenConfig.windows.generators ?? [
'modulesWindows',
];
const jsRootPathRelative = path
.relative(process.cwd(), jsRootDir)
.split(path.sep)
.join('/');
const options: RnwCodeGenOptions = {
files: [
`${jsRootPathRelative}${
jsRootPathRelative ? '/' : ''
}**/*Native*.[jt]s`,
],
componentsWindows: generators.indexOf('componentsWindows') !== -1,
internalComponents: generators.indexOf('internalComponents') !== -1,
cppStringType,
separateDataTypes,
libraryName: projectName,
methodOnly: false,
modulesCxx: generators.indexOf('modulesCxx') !== -1,
modulesTypeScriptTypes:
generators.indexOf('modulesTypeScriptTypes') !== -1,
modulesWindows: generators.indexOf('modulesWindows') !== -1,
namespace: projectNamespace,
outputDirectory: path.join(this.root, codegenOutputDir),
test: !!this.options.check,
};
verboseMessage(
`Run codegen with options: \n${JSON.stringify(options, null, 2)}`,
verbose,
);
this.changesNecessary = runCodeGen(options);
spinner.succeed();
}
}
/**
* Logs the given message if verbose is True.
* @param message The message to log.
* @param verbose Whether or not verbose logging is enabled.
*/
function verboseMessage(message: any, verbose?: boolean) {
if (verbose) {
console.log(message);
}
}
/**
* Sanitizes the given option for telemetry.
* @param key The key of the option.
* @param value The unsanitized value of the option.
* @returns The sanitized value of the option.
*/
function optionSanitizer(key: keyof CodeGenOptions, value: any): any {
// Do not add a default case here.
// Strings risking PII should just return true if present, false otherwise.
// All others should return the value (or false if undefined).
switch (key) {
case 'logging':
case 'check':
case 'telemetry':
return value === undefined ? false : value; // Return value
}
}
/**
* Get the extra props to add to the `codegen-windows` telemetry event.
* @returns The extra props.
*/
async function getExtraProps(): Promise<Record<string, any>> {
const extraProps: Record<string, any> = {};
return extraProps;
}
/**
* The function run when calling `npx @react-native-community/cli codegen-windows`.
* @param args Unprocessed args passed from react-native CLI.
* @param config Config passed from react-native CLI.
* @param options Options passed from react-native CLI.
*/
async function codegenWindows(
args: string[],
config: Config,
options: CodeGenOptions,
) {
await startTelemetrySession(
'codegen-windows',
config,
options,
getDefaultOptions(config, codegenOptions),
optionSanitizer,
);
let codegenWindowsError: Error | undefined;
try {
await codegenWindowsInternal(args, config, options);
} catch (ex) {
codegenWindowsError =
ex instanceof Error ? (ex as Error) : new Error(String(ex));
Telemetry.trackException(codegenWindowsError);
}
await endTelemetrySession(codegenWindowsError, getExtraProps);
setExitProcessWithError(options.logging, codegenWindowsError);
}
/**
* Performs codegen for RNW native modules and apps.
* @param args Unprocessed args passed from react-native CLI.
* @param config Config passed from react-native CLI.
* @param options Options passed from react-native CLI.
*/
export async function codegenWindowsInternal(
args: string[],
config: Config,
options: CodeGenOptions,
existingSpinner?: Ora,
) {
const startTime = performance.now();
const spinner =
existingSpinner ||
newSpinner(
options.check
? 'Checking codegen-windows files...'
: 'Running codegen-windows...',
);
const shouldLog = !existingSpinner; // Only log completion messages if we created our own spinner
try {
const codegen = new CodeGenWindows(config.root, options);
await codegen.run(spinner);
const endTime = performance.now();
if (!codegen.areChangesNeeded()) {
if (shouldLog) {
console.log(
`${chalk.green(
'Success:',
)} No codegen-windows changes necessary. (${Math.round(
endTime - startTime,
)}ms)`,
);
}
} else if (options.check) {
const codegenCommand = 'npx @react-native-community/cli codegen-windows';
if (shouldLog) {
console.log(
`${chalk.yellow(
'Warning:',
)} Codegen-windows changes were necessary but ${chalk.bold(
'--check',
)} specified. Run '${chalk.bold(
`${codegenCommand}`,
)}' to apply the changes. (${Math.round(endTime - startTime)}ms)`,
);
}
throw new CodedError(
'NeedCodegen',
`Codegen-windows changes were necessary but --check was specified. Run '${codegenCommand}' to apply the changes`,
);
} else {
if (shouldLog) {
console.log(
`${chalk.green(
'Success:',
)} Codegen-windows changes completed. (${Math.round(
endTime - startTime,
)}ms)`,
);
}
}
} catch (e) {
if (!existingSpinner) {
spinner.fail();
}
const endTime = performance.now();
if (shouldLog) {
console.log(
`${chalk.red('Error:')} ${(e as any).toString()}. (${Math.round(
endTime - startTime,
)}ms)`,
);
}
throw e;
}
}
/**
* Performs codegen for RNW native modules.
*/
export const codegenCommand: Command = {
name: 'codegen-windows',
description: 'Runs Windows-specific codegen for native modules',
func: codegenWindows,
options: codegenOptions,
};