-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathnative-add.ts
389 lines (320 loc) · 10.3 KB
/
native-add.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
import { IProjectData } from "../definitions/project";
import * as fs from "fs";
import { ICommandParameter, ICommand } from "../common/definitions/commands";
import { IErrors } from "../common/declarations";
import * as path from "path";
import { injector } from "../common/yok";
import { capitalizeFirstLetter } from "../common/utils";
import { EOL } from "os";
export class NativeAddCommand implements ICommand {
public allowedParameters: ICommandParameter[] = [];
constructor(
protected $projectData: IProjectData,
protected $logger: ILogger,
protected $errors: IErrors
) {
this.$projectData.initializeProjectData();
}
public async execute(args: string[]): Promise<void> {
this.failWithUsage();
return Promise.resolve();
}
protected failWithUsage(): void {
this.$errors.failWithHelp(
"Usage: ns native add [swift|objective-c|java|kotlin] [class name]"
);
}
public async canExecute(args: string[]): Promise<boolean> {
this.failWithUsage();
return false;
}
protected getIosSourcePathBase() {
const resources = this.$projectData.getAppResourcesDirectoryPath();
return path.join(resources, "iOS", "src");
}
protected getAndroidSourcePathBase() {
const resources = this.$projectData.getAppResourcesDirectoryPath();
return path.join(resources, "Android", "src", "main", "java");
}
}
export class NativeAddSingleCommand extends NativeAddCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
public async canExecute(args: string[]): Promise<boolean> {
if (!args || args.length !== 1) {
this.failWithUsage();
}
return true;
}
}
export class NativeAddAndroidCommand extends NativeAddSingleCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
private getPackageName(className: string): string {
const lastDotIndex = className.lastIndexOf(".");
if (lastDotIndex !== -1) {
return className.substring(0, lastDotIndex);
}
return "";
}
private getClassSimpleName(className: string): string {
const lastDotIndex = className.lastIndexOf(".");
if (lastDotIndex !== -1) {
return className.substring(lastDotIndex + 1);
}
return className;
}
private generateJavaClassContent(
packageName: string,
classSimpleName: string
): string {
return (
(packageName.length > 0 ? `package ${packageName};` : "") +
`
import android.util.Log;
public class ${classSimpleName} {
public void logMessage() {
Log.d("JS", "Hello from ${classSimpleName}!");
}
}
`
);
}
private generateKotlinClassContent(
packageName: string,
classSimpleName: string
): string {
return (
(packageName.length > 0 ? `package ${packageName};` : "") +
`
import android.util.Log
class ${classSimpleName} {
fun logMessage() {
Log.d("JS", "Hello from ${classSimpleName}!")
}
}
`
);
}
public doJavaKotlin(className: string, extension: string): void {
const fileExt = extension == "java" ? extension : "kt";
const packageName = this.getPackageName(className);
const classSimpleName = this.getClassSimpleName(className);
const packagePath = path.join(
this.getAndroidSourcePathBase(),
...packageName.split(".")
);
const filePath = path.join(packagePath, `${classSimpleName}.${fileExt}`);
if (fs.existsSync(filePath)) {
this.$errors.failWithHelp(
`${extension} file '${filePath}' already exists.`
);
return;
}
if (extension == "kotlin" && !this.checkAndUpdateGradleProperties()) {
return;
}
const fileContent =
extension == "java"
? this.generateJavaClassContent(packageName, classSimpleName)
: this.generateKotlinClassContent(packageName, classSimpleName);
fs.mkdirSync(packagePath, { recursive: true });
fs.writeFileSync(filePath, fileContent);
this.$logger.info(
`${capitalizeFirstLetter(
extension
)} file '${filePath}' generated successfully.`
);
}
private checkAndUpdateGradleProperties(): boolean {
const resources = this.$projectData.getAppResourcesDirectoryPath();
const filePath = path.join(resources, "Android", "gradle.properties");
if (fs.existsSync(filePath)) {
const fileContent = fs.readFileSync(filePath, "utf8");
const propertyRegex = /^useKotlin\s*=\s*(true|false)$/m;
const match = propertyRegex.exec(fileContent);
if (match) {
const useKotlin = match[1];
if (useKotlin === "false") {
this.$errors.failWithHelp(
"The useKotlin property is set to false. Stopping processing. Kotlin must be enabled in gradle.properties to use."
);
return false;
}
if (useKotlin === "true") {
return true;
}
} else {
fs.appendFileSync(filePath, `${EOL}useKotlin=true${EOL}`);
this.$logger.info(
'Added "useKotlin=true" property to gradle.properties.'
);
}
} else {
fs.writeFileSync(filePath, `useKotlin=true${EOL}`);
this.$logger.info(
'Created gradle.properties with "useKotlin=true" property.'
);
}
return true;
}
}
export class NativeAddJavaCommand extends NativeAddAndroidCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
public async execute(args: string[]): Promise<void> {
this.doJavaKotlin(args[0], "java");
return Promise.resolve();
}
}
export class NativeAddKotlinCommand extends NativeAddAndroidCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
public async execute(args: string[]): Promise<void> {
this.doJavaKotlin(args[0], "kotlin");
return Promise.resolve();
}
}
export class NativeAddObjectiveCCommand extends NativeAddSingleCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
public async execute(args: string[]): Promise<void> {
this.doObjectiveC(args[0]);
return Promise.resolve();
}
private doObjectiveC(className: string) {
const iosSourceBase = this.getIosSourcePathBase();
const classFilePath = path.join(iosSourceBase, `${className}.m`);
const headerFilePath = path.join(iosSourceBase, `${className}.h`);
if (
this.generateObjectiveCFiles(className, classFilePath, headerFilePath)
) {
// Modify/Generate moduleMap
this.generateOrUpdateModuleMap(
`${className}.h`,
path.join(iosSourceBase, "module.modulemap")
);
}
}
private generateOrUpdateModuleMap(
headerFileName: string,
moduleMapPath: string
): void {
const moduleName = "LocalModule";
const headerPath = headerFileName;
let moduleMapContent = "";
if (fs.existsSync(moduleMapPath)) {
moduleMapContent = fs.readFileSync(moduleMapPath, "utf8");
}
const headerDeclaration = `header "${headerPath}"`;
if (moduleMapContent.includes(`module ${moduleName}`)) {
// Module declaration already exists in the module map
if (moduleMapContent.includes(headerDeclaration)) {
// Header is already present in the module map
this.$logger.warn(
`Header '${headerFileName}' is already added to the module map.`
);
return;
}
const updatedModuleMapContent = moduleMapContent.replace(
new RegExp(`module ${moduleName} {\\s*([^}]*)\\s*}`, "s"),
`module ${moduleName} {${EOL} $1${EOL} ${headerDeclaration}${EOL}}`
);
fs.writeFileSync(moduleMapPath, updatedModuleMapContent);
} else {
// Module declaration does not exist in the module map
const moduleDeclaration = `module ${moduleName} {${EOL} ${headerDeclaration}${EOL} export *${EOL}}`;
moduleMapContent += `${EOL}${EOL}${moduleDeclaration}`;
fs.writeFileSync(moduleMapPath, moduleMapContent);
}
this.$logger.info(
`Module map '${moduleMapPath}' has been updated with the header '${headerFileName}'.`
);
}
private generateObjectiveCFiles(
className: string,
classFilePath: string,
interfaceFilePath: string
): boolean {
if (fs.existsSync(classFilePath)) {
this.$errors.failWithHelp(
`Error: File '${classFilePath}' already exists.`
);
return false;
}
if (fs.existsSync(interfaceFilePath)) {
this.$errors.failWithHelp(
`Error: File '${interfaceFilePath}' already exists.`
);
return false;
}
const interfaceContent = `#import <Foundation/Foundation.h>
@interface ${className} : NSObject
- (void)logMessage;
@end
`;
const classContent = `#import "${className}.h"
@implementation ${className}
- (void)logMessage {
NSLog(@"Hello from ${className} class!");
}
@end
`;
fs.writeFileSync(classFilePath, classContent);
this.$logger.trace(
`Objective-C class file '${classFilePath}' generated successfully.`
);
fs.writeFileSync(interfaceFilePath, interfaceContent);
this.$logger.trace(
`Objective-C interface file '${interfaceFilePath}' generated successfully.`
);
return true;
}
}
export class NativeAddSwiftCommand extends NativeAddSingleCommand {
constructor($projectData: IProjectData, $logger: ILogger, $errors: IErrors) {
super($projectData, $logger, $errors);
}
public async execute(args: string[]): Promise<void> {
this.doSwift(args[0]);
return Promise.resolve();
}
private doSwift(className: string) {
const iosSourceBase = this.getIosSourcePathBase();
const swiftFilePath = path.join(iosSourceBase, `${className}.swift`);
this.generateSwiftFile(className, swiftFilePath);
}
private generateSwiftFile(className: string, filePath: string): void {
const directory = path.dirname(filePath);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
this.$logger.trace(`Created directory: '${directory}'.`);
}
if (fs.existsSync(filePath)) {
this.$errors.failWithHelp(`Error: File '${filePath}' already exists.`);
return;
}
const content = `import Foundation;
import os;
@objc class ${className}: NSObject {
@objc func logMessage() {
os_log("Hello from ${className} class!")
}
}`;
fs.writeFileSync(filePath, content);
this.$logger.info(`Swift file '${filePath}' generated successfully.`);
}
}
injector.registerCommand(["native|add"], NativeAddCommand);
injector.registerCommand(["native|add|java"], NativeAddJavaCommand);
injector.registerCommand(["native|add|kotlin"], NativeAddKotlinCommand);
injector.registerCommand(["native|add|swift"], NativeAddSwiftCommand);
injector.registerCommand(
["native|add|objective-c"],
NativeAddObjectiveCCommand
);