-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathandroid-project-service.ts
224 lines (189 loc) · 8.2 KB
/
android-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
///<reference path="../.d.ts"/>
import path = require("path");
import shell = require("shelljs");
import util = require("util");
import options = require("./../options");
import helpers = require("./../common/helpers");
import constants = require("./../constants");
class AndroidProjectService implements IPlatformProjectService {
private targetApi: string;
constructor(private $fs: IFileSystem,
private $errors: IErrors,
private $logger: ILogger,
private $childProcess: IChildProcess,
private $projectData: IProjectData,
private $propertiesParser: IPropertiesParser) { }
public validate(): IFuture<void> {
return (() => {
this.validatePackageName(this.$projectData.projectId);
this.validateProjectName(this.$projectData.projectName);
this.checkAnt().wait() && this.checkAndroid().wait() && this.checkJava().wait();
}).future<void>()();
}
public createProject(projectRoot: string, frameworkDir: string): IFuture<void> {
return (() => {
this.validateAndroidTarget(frameworkDir); // We need framework to be installed to validate android target so we can't call this method in validate()
var paths = "assets gen libs res".split(' ').map(p => path.join(frameworkDir, p));
shell.cp("-r", paths, projectRoot);
paths = ".project AndroidManifest.xml project.properties".split(' ').map(p => path.join(frameworkDir, p));
shell.cp("-f", paths, projectRoot);
// Create src folder
var packageName = this.$projectData.projectId;
var packageAsPath = packageName.replace(/\./g, path.sep);
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 manifestPath = path.join(projectRoot, "AndroidManifest.xml");
var safeActivityName = this.$projectData.projectName.replace(/\W/g, '');
shell.sed('-i', /__PACKAGE__/, this.$projectData.projectId, manifestPath);
shell.sed('-i', /__ACTIVITY__/, safeActivityName, manifestPath);
shell.sed('-i', /__APILEVEL__/, this.getTarget(projectRoot).wait().split('-')[1], manifestPath);
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'));
}).future<void>()();
}
public afterCreateProject(projectRoot: string) {
var targetApi = this.getTarget(projectRoot).wait();
this.$logger.trace("Android target: %s", targetApi);
this.runAndroidUpdate(projectRoot, targetApi).wait();
}
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, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME);
shell.cp("-r", path.join(this.$projectData.projectDir, constants.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, constants.APP_FOLDER_NAME));
var platformsAsString = platforms.join("|");
_.each(files, fileName => {
var platformInfo = AndroidProjectService.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>()();
}
public buildProject(projectRoot: string): IFuture<void> {
return (() => {
var buildConfiguration = options.release ? "release" : "debug";
var args = this.getAntArgs(buildConfiguration, projectRoot);
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 (() => {
var args = [
"--path", projectPath,
"--target", targetApi
];
this.spawn("android update project", args);
}).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 validateAndroidTarget(frameworkDir: string) {
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]);
}
}
private getTarget(projectRoot: string): IFuture<string> {
return (() => {
if(!this.targetApi) {
var projectPropertiesFilePath = path.join(projectRoot, "project.properties");
if (this.$fs.exists(projectPropertiesFilePath).wait()) {
var properties = this.$propertiesParser.createEditor(projectPropertiesFilePath).wait();
this.targetApi = properties.get("target");
}
}
return this.targetApi;
}).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>()();
}
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;
}
}
$injector.register("androidProjectService", AndroidProjectService);