-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathproject-service.ts
502 lines (414 loc) · 18.5 KB
/
project-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
///<reference path="../.d.ts"/>
import path = require("path");
import options = require("./../options");
import shell = require("shelljs");
import osenv = require("osenv");
import util = require("util");
import helpers = require("./../common/helpers");
class ProjectData implements IProjectData {
public projectDir: string;
public platformsDir: string;
public projectFilePath: string;
public projectId: string;
public projectName: string;
constructor(private $fs: IFileSystem,
private $projectHelper: IProjectHelper,
private $config) {
this.initializeProjectData().wait();
}
private initializeProjectData(): IFuture<void> {
return(() => {
var projectDir = this.$projectHelper.projectDir;
if(projectDir) {
this.projectDir = projectDir;
this.projectName = path.basename(projectDir);
this.platformsDir = path.join(projectDir, "platforms");
this.projectFilePath = path.join(projectDir, this.$config.PROJECT_FILE_NAME);
if (this.$fs.exists(this.projectFilePath).wait()) {
var fileContent = this.$fs.readJson(this.projectFilePath).wait();
this.projectId = fileContent.id;
}
}
}).future<void>()();
}
}
$injector.register("projectData", ProjectData);
export class ProjectService implements IProjectService {
private static DEFAULT_PROJECT_ID = "com.telerik.tns.HelloWorld";
private static DEFAULT_PROJECT_NAME = "HelloNativescript";
public static APP_FOLDER_NAME = "app";
constructor(private $logger: ILogger,
private $errors: IErrors,
private $fs: IFileSystem,
private $projectTemplatesService: IProjectTemplatesService,
private $projectData: IProjectData,
private $config) { }
public createProject(projectName: string, projectId: string): IFuture<void> {
return(() => {
var projectDir = path.resolve(options.path || ".");
projectId = projectId || ProjectService.DEFAULT_PROJECT_ID;
projectName = projectName || ProjectService.DEFAULT_PROJECT_NAME;
projectDir = path.join(projectDir, projectName);
this.$fs.createDirectory(projectDir).wait();
var customAppPath = this.getCustomAppPath();
if(customAppPath) {
customAppPath = path.resolve(customAppPath);
}
if(this.$fs.exists(projectDir).wait() && !this.$fs.isEmptyDir(projectDir).wait()) {
this.$errors.fail("Path already exists and is not empty %s", projectDir);
}
this.$logger.trace("Creating a new NativeScript project with name %s and id %s at location %s", projectName, projectId, projectDir);
var appDirectory = path.join(projectDir, ProjectService.APP_FOLDER_NAME);
var appPath: string = null;
if(customAppPath) {
this.$logger.trace("Using custom app from %s", customAppPath);
// Make sure that the source app/ is not a direct ancestor of a target app/
var relativePathFromSourceToTarget = path.relative(customAppPath, appDirectory);
var doesRelativePathGoUpAtLeastOneDir = relativePathFromSourceToTarget.split(path.sep)[0] == "..";
if(!doesRelativePathGoUpAtLeastOneDir) {
this.$errors.fail("Project dir %s must not be created at/inside the template used to create the project %s.", projectDir, customAppPath);
}
this.$logger.trace("Copying custom app into %s", appDirectory);
appPath = customAppPath;
} else {
// No custom app - use nativescript hello world application
this.$logger.trace("Using NativeScript hello world application");
var defaultTemplatePath = this.$projectTemplatesService.defaultTemplatePath.wait();
this.$logger.trace("Copying Nativescript hello world application into %s", appDirectory);
appPath = defaultTemplatePath;
}
this.createProjectCore(projectDir, appPath, projectId, false).wait();
}).future<void>()();
}
private createProjectCore(projectDir: string, appPath: string, projectId: string, symlink?: boolean): IFuture<void> {
return (() => {
if(!this.$fs.exists(projectDir).wait()) {
this.$fs.createDirectory(projectDir).wait();
}
if(symlink) {
// TODO: Implement support for symlink the app folder instead of copying
} else {
var appDir = path.join(projectDir, ProjectService.APP_FOLDER_NAME);
this.$fs.createDirectory(appDir).wait();
shell.cp('-R', path.join(appPath, "*"), appDir);
}
this.createBasicProjectStructure(projectDir, projectId).wait();
}).future<void>()();
}
private createBasicProjectStructure(projectDir: string, projectId: string): IFuture<void> {
return (() => {
this.$fs.createDirectory(path.join(projectDir, "platforms")).wait();
this.$fs.createDirectory(path.join(projectDir, "tns_modules")).wait();
this.$fs.createDirectory(path.join(projectDir, "hooks")).wait();
var projectData = { id: projectId };
this.$fs.writeFile(path.join(projectDir, this.$config.PROJECT_FILE_NAME), JSON.stringify(projectData)).wait();
}).future<void>()();
}
private getCustomAppPath(): string {
var customAppPath = options["copy-from"] || options["link-to"];
if(customAppPath) {
if(customAppPath.indexOf("http") >= 0) {
this.$errors.fail("Only local paths for custom app are supported.");
}
if(customAppPath.substr(0, 1) === '~') {
customAppPath = path.join(osenv.home(), customAppPath.substr(1));
}
}
return customAppPath;
}
public ensureProject() {
if (this.$projectData.projectDir === "" || !this.$fs.exists(this.$projectData.projectFilePath).wait()) {
this.$errors.fail("No project found at or above '%s' and neither was a --path specified.", process.cwd());
}
}
}
$injector.register("projectService", ProjectService);
class PlatformProjectService implements IPlatformProjectService {
private static APP_RESOURCES_FOLDER_NAME = "App_Resources";
public static PROJECT_FRAMEWORK_DIR = "framework";
constructor(private $npm: INodePackageManager,
private $platformsData: IPlatformsData,
private $projectData: IProjectData,
private $logger: ILogger,
private $fs: IFileSystem) { }
public createProject(platform: string): IFuture<void> {
return(() => {
var platformData = this.$platformsData.getPlatformData(platform);
var platformProjectService = platformData.platformProjectService;
platformProjectService.validate();
// get path to downloaded framework package
var frameworkDir = this.$npm.downloadNpmPackage(this.$platformsData.getPlatformData(platform).frameworkPackageName,
path.join(this.$projectData.platformsDir, platform)).wait();
frameworkDir = path.join(frameworkDir, PlatformProjectService.PROJECT_FRAMEWORK_DIR);
platformProjectService.checkRequirements().wait();
// Log the values for project
this.$logger.trace("Creating NativeScript project for the %s platform", platform);
this.$logger.trace("Path: %s", platformData.projectRoot);
this.$logger.trace("Package: %s", this.$projectData.projectId);
this.$logger.trace("Name: %s", this.$projectData.projectName);
this.$logger.out("Copying template files...");
platformProjectService.createProject(platformData.projectRoot, frameworkDir).wait();
// Need to remove unneeded node_modules folder
this.$fs.deleteDirectory(path.join(this.$projectData.platformsDir, platform, "node_modules")).wait();
platformProjectService.interpolateData(platformData.projectRoot);
platformProjectService.executePlatformSpecificAction(platformData.projectRoot, frameworkDir);
this.$logger.out("Project successfully created.");
}).future<void>()();
}
public prepareProject(normalizedPlatformName: string, platforms: string[]): IFuture<void> {
return (() => {
var platform = normalizedPlatformName.toLowerCase();
var assetsDirectoryPath = path.join(this.$projectData.platformsDir, platform, "assets");
var appResourcesDirectoryPath = path.join(assetsDirectoryPath, ProjectService.APP_FOLDER_NAME, PlatformProjectService.APP_RESOURCES_FOLDER_NAME);
shell.cp("-r", path.join(this.$projectData.projectDir, ProjectService.APP_FOLDER_NAME), assetsDirectoryPath);
if(this.$fs.exists(appResourcesDirectoryPath).wait()) {
shell.cp("-r", path.join(appResourcesDirectoryPath, normalizedPlatformName, "*"), path.join(this.$projectData.platformsDir, platform, "res"));
this.$fs.deleteDirectory(appResourcesDirectoryPath).wait();
}
var files = helpers.enumerateFilesInDirectorySync(path.join(assetsDirectoryPath, ProjectService.APP_FOLDER_NAME));
var platformsAsString = platforms.join("|");
_.each(files, fileName => {
var platformInfo = PlatformProjectService.parsePlatformSpecificFileName(path.basename(fileName), platformsAsString);
var shouldExcludeFile = platformInfo && platformInfo.platform !== platform;
if(shouldExcludeFile) {
this.$fs.deleteFile(fileName).wait();
} else if(platformInfo && platformInfo.onDeviceName) {
this.$fs.rename(fileName, path.join(path.dirname(fileName), platformInfo.onDeviceName)).wait();
}
});
}).future<void>()();
}
private static parsePlatformSpecificFileName(fileName: string, platforms: string): any {
var regex = util.format("^(.+?)\.(%s)(\..+?)$", platforms);
var parsed = fileName.toLowerCase().match(new RegExp(regex, "i"));
if (parsed) {
return {
platform: parsed[2],
onDeviceName: parsed[1] + parsed[3]
};
}
return undefined;
}
public buildProject(platform: string): IFuture<void> {
return (() => {
var platformData = this.$platformsData.getPlatformData(platform);
platformData.platformProjectService.buildProject(platformData.projectRoot).wait();
this.$logger.out("Project successfully built");
}).future<void>()();
}
}
$injector.register("platformProjectService", PlatformProjectService);
class AndroidProjectService implements IPlatformSpecificProjectService {
constructor(private $fs: IFileSystem,
private $errors: IErrors,
private $logger: ILogger,
private $childProcess: IChildProcess,
private $projectData: IProjectData,
private $propertiesParser: IPropertiesParser) { }
public validate(): void {
this.validatePackageName(this.$projectData.projectId);
this.validateProjectName(this.$projectData.projectName);
}
public checkRequirements(): IFuture<void> {
return (() => {
this.checkAnt().wait() && this.checkAndroid().wait() && this.checkJava().wait();
}).future<void>()();
}
public createProject(projectRoot: string, frameworkDir: string): IFuture<void> {
return (() => {
var packageName = this.$projectData.projectId;
var packageAsPath = packageName.replace(/\./g, path.sep);
var validTarget = this.getTarget(frameworkDir).wait();
var output = this.$childProcess.exec('android list targets').wait();
if (!output.match(validTarget)) {
this.$errors.fail("Please install Android target %s the Android newest SDK). Make sure you have the latest Android tools installed as well. Run \"android\" from your command-line to install/update any missing SDKs or tools.",
validTarget.split('-')[1]);
}
shell.cp("-r", path.join(frameworkDir, "assets"), projectRoot);
shell.cp("-r", path.join(frameworkDir, "gen"), projectRoot);
shell.cp("-r", path.join(frameworkDir, "libs"), projectRoot);
shell.cp("-r", path.join(frameworkDir, "res"), projectRoot);
shell.cp("-f", path.join(frameworkDir, ".project"), projectRoot);
shell.cp("-f", path.join(frameworkDir, "AndroidManifest.xml"), projectRoot);
// Create src folder
var activityDir = path.join(projectRoot, 'src', packageAsPath);
this.$fs.createDirectory(activityDir).wait();
}).future<any>()();
}
public interpolateData(projectRoot: string): IFuture<void> {
return (() => {
// Interpolate the activity name and package
var stringsFilePath = path.join(projectRoot, 'res', 'values', 'strings.xml');
shell.sed('-i', /__NAME__/, this.$projectData.projectName, stringsFilePath);
shell.sed('-i', /__TITLE_ACTIVITY__/, this.$projectData.projectName, stringsFilePath);
shell.sed('-i', /__NAME__/, this.$projectData.projectName, path.join(projectRoot, '.project'));
shell.sed('-i', /__PACKAGE__/, this.$projectData.projectId, path.join(projectRoot, "AndroidManifest.xml"));
}).future<void>()();
}
public executePlatformSpecificAction(projectRoot: string, frameworkDir: string) {
var targetApi = this.getTarget(frameworkDir).wait();
this.$logger.trace("Android target: %s", targetApi);
this.runAndroidUpdate(projectRoot, targetApi).wait();
}
public buildProject(projectRoot: string): IFuture<void> {
return (() => {
var buildConfiguration = options.release || "--debug";
var args = this.getAntArgs(buildConfiguration, projectRoot);
switch(buildConfiguration) {
case "--debug":
args[0] = "debug";
break;
case "--release":
args[0] = "release";
break;
default:
this.$errors.fail("Build option %s not recognized", buildConfiguration);
}
this.spawn('ant', args);
}).future<void>()();
}
private spawn(command: string, args: string[], options?: any): void {
if(helpers.isWindows()) {
args.unshift('/s', '/c', command);
command = 'cmd';
}
this.$childProcess.spawn(command, args, {cwd: options, stdio: 'inherit'});
}
private getAntArgs(configuration: string, projectRoot: string): string[] {
var args = [configuration, "-f", path.join(projectRoot, "build.xml")];
return args;
}
private runAndroidUpdate(projectPath: string, targetApi: string): IFuture<void> {
return (() => {
this.$childProcess.exec("android update project --subprojects --path " + projectPath + " --target " + targetApi).wait();
}).future<void>()();
}
private validatePackageName(packageName: string): void {
//Make the package conform to Java package types
//Enforce underscore limitation
if (!/^[a-zA-Z]+(\.[a-zA-Z0-9][a-zA-Z0-9_]*)+$/.test(packageName)) {
this.$errors.fail("Package name must look like: com.company.Name");
}
//Class is a reserved word
if(/\b[Cc]lass\b/.test(packageName)) {
this.$errors.fail("class is a reserved word");
}
}
private validateProjectName(projectName: string): void {
if (projectName === '') {
this.$errors.fail("Project name cannot be empty");
}
//Classes in Java don't begin with numbers
if (/^[0-9]/.test(projectName)) {
this.$errors.fail("Project name must not begin with a number");
}
}
private getTarget(frameworkDir: string): IFuture<string> {
return (() => {
var projectPropertiesFilePath = path.join(frameworkDir, "project.properties");
if (this.$fs.exists(projectPropertiesFilePath).wait()) {
var properties = this.$propertiesParser.createEditor(projectPropertiesFilePath).wait();
return properties.get("target");
}
return "";
}).future<string>()();
}
private checkAnt(): IFuture<void> {
return (() => {
try {
this.$childProcess.exec("ant -version").wait();
} catch(error) {
this.$errors.fail("Error executing commands 'ant', make sure you have ant installed and added to your PATH.")
}
}).future<void>()();
}
private checkJava(): IFuture<void> {
return (() => {
try {
this.$childProcess.exec("java -version").wait();
} catch(error) {
this.$errors.fail("%s\n Failed to run 'java', make sure your java environment is set up.\n Including JDK and JRE.\n Your JAVA_HOME variable is %s", error, process.env.JAVA_HOME);
}
}).future<void>()();
}
private checkAndroid(): IFuture<void> {
return (() => {
try {
this.$childProcess.exec('android list targets').wait();
} catch(error) {
if (error.match(/command\snot\sfound/)) {
this.$errors.fail("The command \"android\" failed. Make sure you have the latest Android SDK installed, and the \"android\" command (inside the tools/ folder) is added to your path.");
} else {
this.$errors.fail("An error occurred while listing Android targets");
}
}
}).future<void>()();
}
}
$injector.register("androidProjectService", AndroidProjectService);
class IOSProjectService implements IPlatformSpecificProjectService {
private static PROJECT_NAME_PLACEHOLDER = "__PROJECT_NAME__";
constructor(private $childProcess: IChildProcess,
private $projectData: IProjectData,
private $fs: IFileSystem,
private $errors: IErrors) { }
public validate(): void { }
public checkRequirements(): IFuture<void> {
return (() => {
try {
this.$childProcess.exec("which xcodebuild").wait();
} catch(error) {
this.$errors.fail("The command 'which xcodebuild' failed. Make sure you have the Xcode installed");
}
}).future<void>()();
}
public interpolateData(projectRoot: string): IFuture<void> {
return (() => {
this.replaceFileName("-Info.plist", projectRoot).wait();
this.replaceFileName("-Prefix.pch", projectRoot).wait();
this.replaceFileName(".xcodeproj", this.$projectData.platformsDir).wait();
/* this.$fs.rename(path.join(this.$projectData.platformsDir, IOSProjectService.PROJECT_NAME_PLACEHOLDER + ".xcodeproj"),
path.join(this.$projectData.platformsDir, this.$projectData.projectName + ".xcodeproj")).wait(); */
var pbxprojFilePath = path.join(this.$projectData.platformsDir, this.$projectData.projectName + ".xcodeproj", "project.pbxproj");
this.replaceFileContent(pbxprojFilePath).wait();
}).future<void>()();
}
public createProject(projectRoot: string, frameworkDir: string): IFuture<void> {
return (() => {
shell.cp("-r", path.join(frameworkDir, "*"), this.$projectData.platformsDir);
this.$fs.rename(path.join(this.$projectData.platformsDir, IOSProjectService.PROJECT_NAME_PLACEHOLDER), projectRoot).wait();
}).future<void>()();
}
public buildProject(projectRoot: string): IFuture<void> {
return (() => {
var args = [
"-project", path.join(this.$projectData.platformsDir, "ios", this.$projectData.projectName + ".xcodeproj"),
"-target", this.$projectData.projectName,
"-configuration", options.release || "Debug",
"-sdk", "iphonesimulator",
"build",
"ARCHS=\"armv7 armv7s arm64\"",
"VALID_ARCHS=\"armv7 armv7s arm64\"",
"CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build") + ""
];
this.$childProcess.spawn("xcodebuild", args, {cwd: options, stdio: 'inherit'});
}).future<void>()();
}
public executePlatformSpecificAction(projectRoot: string, frameworkDir: string): void {
}
private replaceFileContent(file: string): IFuture<void> {
return (() => {
var fileContent = this.$fs.readText(file).wait();
var replacedContent = helpers.stringReplaceAll(fileContent, IOSProjectService.PROJECT_NAME_PLACEHOLDER, this.$projectData.projectName);
this.$fs.writeFile(file, replacedContent).wait();
}).future<void>()();
}
private replaceFileName(fileNamePart: string, projectRoot: string): IFuture<void> {
return (() => {
var oldFileName = IOSProjectService.PROJECT_NAME_PLACEHOLDER + fileNamePart;
var newFileName = this.$projectData.projectName + fileNamePart;
this.$fs.rename(path.join(projectRoot, oldFileName), path.join(projectRoot, newFileName)).wait();
}).future<void>()();
}
}
$injector.register("iOSProjectService", IOSProjectService);