-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathplugins-service.ts
268 lines (223 loc) · 10.3 KB
/
plugins-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
///<reference path="../.d.ts"/>
"use strict";
import path = require("path");
import shelljs = require("shelljs");
import semver = require("semver");
import Future = require("fibers/future");
import constants = require("./../constants");
let xmlmerge = require("xmlmerge-js");
let DOMParser = require('xmldom').DOMParser;
export class PluginsService implements IPluginsService {
private static INSTALL_COMMAND_NAME = "install";
private static UNINSTALL_COMMAND_NAME = "uninstall";
private static NPM_CONFIG = {
save: true
}
constructor(private $platformsData: IPlatformsData,
private $npm: INodePackageManager,
private $fs: IFileSystem,
private $projectData: IProjectData,
private $projectDataService: IProjectDataService,
private $childProcess: IChildProcess,
private $options: IOptions,
private $logger: ILogger,
private $errors: IErrors,
private $projectFilesManager: IProjectFilesManager) { }
public add(plugin: string): IFuture<void> {
return (() => {
let dependencies = this.getAllInstalledModules().wait();
let dependencyData = this.$npm.cache(plugin, undefined, PluginsService.NPM_CONFIG).wait();
if(dependencyData.nativescript) {
let pluginName = this.executeNpmCommand(PluginsService.INSTALL_COMMAND_NAME, plugin).wait();
this.prepare(dependencyData).wait();
this.$logger.out(`Successfully installed plugin ${dependencyData.name}.`);
} else {
this.$errors.failWithoutHelp(`${plugin} is not a valid NativeScript plugin. Verify that the plugin package.json file contains a nativescript key and try again.`);
}
}).future<void>()();
}
public remove(pluginName: string): IFuture<void> {
return (() => {
let removePluginNativeCodeAction = (modulesDestinationPath: string, platform: string, platformData: IPlatformData) => {
let pluginData = this.convertToPluginData(this.getNodeModuleData(pluginName).wait());
pluginData.isPlugin = true;
return platformData.platformProjectService.removePluginNativeCode(pluginData);
};
this.executeForAllInstalledPlatforms(removePluginNativeCodeAction).wait();
this.executeNpmCommand(PluginsService.UNINSTALL_COMMAND_NAME, pluginName).wait();
let showMessage = true;
let action = (modulesDestinationPath: string, platform: string, platformData: IPlatformData) => {
return (() => {
shelljs.rm("-rf", path.join(modulesDestinationPath, pluginName));
this.$logger.out(`Successfully removed plugin ${pluginName} for ${platform}.`);
showMessage = false;
}).future<void>()();
};
this.executeForAllInstalledPlatforms(action).wait();
if(showMessage) {
this.$logger.out(`Succsessfully removed plugin ${pluginName}`);
}
}).future<void>()();
}
public prepare(dependencyData: IDependencyData): IFuture<void> {
return (() => {
let pluginData = this.convertToPluginData(dependencyData);
let action = (pluginDestinationPath: string, platform: string, platformData: IPlatformData) => {
return (() => {
// Process .js files
let installedFrameworkVersion = this.getInstalledFrameworkVersion(platform).wait();
let pluginPlatformsData = pluginData.platformsData;
if(pluginPlatformsData) {
let pluginVersion = (<any>pluginPlatformsData)[platform];
if(!pluginVersion) {
this.$logger.warn(`${pluginData.name} is not supported for ${platform}.`);
return;
}
if(semver.gt(pluginVersion, installedFrameworkVersion)) {
this.$logger.warn(`${pluginData.name} ${pluginVersion} for ${platform} is not compatible with the currently installed framework version ${installedFrameworkVersion}.`);
return;
}
}
this.$fs.ensureDirectoryExists(pluginDestinationPath).wait();
shelljs.cp("-Rf", pluginData.fullPath, pluginDestinationPath);
let pluginPlatformsFolderPath = path.join(pluginDestinationPath, pluginData.name, "platforms", platform);
let pluginConfigurationFilePath = path.join(pluginPlatformsFolderPath, platformData.configurationFileName);
let configurationFilePath = platformData.configurationFilePath;
if(this.$fs.exists(pluginConfigurationFilePath).wait()) {
// Validate plugin configuration file
let pluginConfigurationFileContent = this.$fs.readText(pluginConfigurationFilePath).wait();
this.validateXml(pluginConfigurationFileContent, pluginConfigurationFilePath);
// Validate configuration file
let configurationFileContent = this.$fs.readText(configurationFilePath).wait();
this.validateXml(configurationFileContent, configurationFilePath);
// Merge xml
let resultXml = this.mergeXml(configurationFileContent, pluginConfigurationFileContent, platformData.mergeXmlConfig || []).wait();
this.validateXml(resultXml);
this.$fs.writeFile(configurationFilePath, resultXml).wait();
}
this.$projectFilesManager.processPlatformSpecificFiles(pluginDestinationPath, platform).wait();
pluginData.pluginPlatformsFolderPath = (platform: string) => path.join(pluginData.fullPath, "platforms", platform);
platformData.platformProjectService.preparePluginNativeCode(pluginData).wait();
// Show message
this.$logger.out(`Successfully prepared plugin ${pluginData.name} for ${platform}.`);
}).future<void>()();
};
this.executeForAllInstalledPlatforms(action).wait();
}).future<void>()();
}
public ensureAllDependenciesAreInstalled(): IFuture<void> {
return this.$childProcess.exec("npm install ", { cwd: this.$projectData.projectDir });
}
public getAllInstalledPlugins(): IFuture<IPluginData[]> {
return (() => {
let nodeModules = this.getAllInstalledModules().wait();
return _.filter(nodeModules, nodeModuleData => nodeModuleData && nodeModuleData.isPlugin);
}).future<IPluginData[]>()();
}
private get nodeModulesPath(): string {
return path.join(this.$projectData.projectDir, "node_modules");
}
private getPackageJsonFilePath(): string {
return path.join(this.$projectData.projectDir, "package.json");
}
private getPackageJsonFilePathForModule(moduleName: string): string {
return path.join(this.nodeModulesPath, moduleName, "package.json");
}
private getDependencies(): string[] {
let packageJsonFilePath = this.getPackageJsonFilePath();
return _.keys(require(packageJsonFilePath).dependencies);
}
private getNodeModuleData(moduleName: string): IFuture<INodeModuleData> {
return (() => {
let packageJsonFilePath = this.getPackageJsonFilePathForModule(moduleName);
if(this.$fs.exists(packageJsonFilePath).wait()) {
let data = require(packageJsonFilePath);
return {
name: data.name,
version: data.version,
fullPath: path.dirname(packageJsonFilePath),
isPlugin: data.nativescript !== undefined,
moduleInfo: data.nativescript
};
}
return null;
}).future<INodeModuleData>()();
}
private convertToPluginData(cacheData: any): IPluginData {
let pluginData: any = {};
pluginData.name = cacheData.name;
pluginData.version = cacheData.version;
pluginData.fullPath = path.dirname(this.getPackageJsonFilePathForModule(cacheData.name));
pluginData.isPlugin = !!cacheData.nativescript;
pluginData.pluginPlatformsFolderPath = (platform: string) => path.join(pluginData.fullPath, "platforms", platform);
if(pluginData.isPlugin) {
pluginData.platformsData = cacheData.nativescript.platforms;
}
return pluginData;
}
private getAllInstalledModules(): IFuture<INodeModuleData[]> {
return (() => {
this.ensureAllDependenciesAreInstalled().wait();
this.$fs.ensureDirectoryExists(this.nodeModulesPath).wait();
let nodeModules = this.getDependencies();
return _.map(nodeModules, nodeModuleName => this.getNodeModuleData(nodeModuleName).wait());
}).future<INodeModuleData[]>()();
}
private executeNpmCommand(npmCommandName: string, npmCommandArguments: string): IFuture<string> {
return (() => {
let result = "";
if(npmCommandName === PluginsService.INSTALL_COMMAND_NAME) {
result = this.$npm.install(npmCommandArguments, this.$projectData.projectDir, PluginsService.NPM_CONFIG).wait();
} else if(npmCommandName === PluginsService.UNINSTALL_COMMAND_NAME) {
result = this.$npm.uninstall(npmCommandArguments, PluginsService.NPM_CONFIG).wait();
}
return this.parseNpmCommandResult(result);
}).future<string>()();
}
private parseNpmCommandResult(npmCommandResult: string): string { // [[name@version, node_modules/name]]
return npmCommandResult[0][0].split("@")[0]; // returns plugin name
}
private executeForAllInstalledPlatforms(action: (pluginDestinationPath: string, pl: string, platformData: IPlatformData) => IFuture<void>): IFuture<void> {
return (() => {
let availablePlatforms = _.keys(this.$platformsData.availablePlatforms);
_.each(availablePlatforms, platform => {
let isPlatformInstalled = this.$fs.exists(path.join(this.$projectData.platformsDir, platform.toLowerCase())).wait();
if(isPlatformInstalled) {
let platformData = this.$platformsData.getPlatformData(platform.toLowerCase());
let pluginDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules");
action(pluginDestinationPath, platform.toLowerCase(), platformData).wait();
}
});
}).future<void>()();
}
private getInstalledFrameworkVersion(platform: string): IFuture<string> {
return (() => {
let platformData = this.$platformsData.getPlatformData(platform);
this.$projectDataService.initialize(this.$projectData.projectDir);
let frameworkData = this.$projectDataService.getValue(platformData.frameworkPackageName).wait();
return frameworkData.version;
}).future<string>()();
}
private mergeXml(xml1: string, xml2: string, config: any[]): IFuture<string> {
let future = new Future<string>();
try {
xmlmerge.merge(xml1, xml2, config, (mergedXml: string) => {
future.return(mergedXml);
});
} catch(err) {
future.throw(err);
}
return future;
}
private validateXml(xml: string, xmlFilePath?: string): void {
let doc = new DOMParser({
locator: {},
errorHandler: (level: any, msg: string) => {
let errorMessage = xmlFilePath ? `Invalid xml file ${xmlFilePath}.` : `Invalid xml ${xml}.`;
this.$errors.fail(errorMessage + ` Additional technical information: ${msg}.` )
}
});
doc.parseFromString(xml, 'text/xml');
}
}
$injector.register("pluginsService", PluginsService);