-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathplugins-service.ts
355 lines (291 loc) · 15.5 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
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
import * as path from "path";
import * as shelljs from "shelljs";
import * as semver from "semver";
import * as constants from "../constants";
export class PluginsService implements IPluginsService {
private static INSTALL_COMMAND_NAME = "install";
private static UNINSTALL_COMMAND_NAME = "uninstall";
private static NPM_CONFIG = {
save: true
};
private get $platformsDataService(): IPlatformsDataService {
return this.$injector.resolve("platformsDataService");
}
private get $projectDataService(): IProjectDataService {
return this.$injector.resolve("projectDataService");
}
private get npmInstallOptions(): INodePackageManagerInstallOptions {
return _.merge({
disableNpmInstall: this.$options.disableNpmInstall,
frameworkPath: this.$options.frameworkPath,
ignoreScripts: this.$options.ignoreScripts,
path: this.$options.path
}, PluginsService.NPM_CONFIG);
}
constructor(private $packageManager: INodePackageManager,
private $fs: IFileSystem,
private $options: IOptions,
private $logger: ILogger,
private $errors: IErrors,
private $filesHashService: IFilesHashService,
private $injector: IInjector,
private $mobileHelper: Mobile.IMobileHelper) { }
public async add(plugin: string, projectData: IProjectData): Promise<void> {
await this.ensure(projectData);
const possiblePackageName = path.resolve(plugin);
if (possiblePackageName.indexOf(".tgz") !== -1 && this.$fs.exists(possiblePackageName)) {
plugin = possiblePackageName;
}
const name = (await this.$packageManager.install(plugin, projectData.projectDir, this.npmInstallOptions)).name;
const pathToRealNpmPackageJson = this.getPackageJsonFilePathForModule(name, projectData.projectDir);
const realNpmPackageJson = this.$fs.readJson(pathToRealNpmPackageJson);
if (realNpmPackageJson.nativescript) {
const pluginData = this.convertToPluginData(realNpmPackageJson, projectData.projectDir);
// Validate
const action = async (pluginDestinationPath: string, platform: string, platformData: IPlatformData): Promise<void> => {
this.isPluginDataValidForPlatform(pluginData, platform, projectData);
};
await this.executeForAllInstalledPlatforms(action, projectData);
this.$logger.info(`Successfully installed plugin ${realNpmPackageJson.name}.`);
} else {
await this.$packageManager.uninstall(realNpmPackageJson.name, { save: true }, projectData.projectDir);
this.$errors.fail(`${plugin} is not a valid NativeScript plugin. Verify that the plugin package.json file contains a nativescript key and try again.`);
}
}
public async remove(pluginName: string, projectData: IProjectData): Promise<void> {
const removePluginNativeCodeAction = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise<void> => {
const pluginData = this.convertToPluginData(this.getNodeModuleData(pluginName, projectData.projectDir), projectData.projectDir);
await platformData.platformProjectService.removePluginNativeCode(pluginData, projectData);
};
await this.executeForAllInstalledPlatforms(removePluginNativeCodeAction, projectData);
await this.executeNpmCommand(PluginsService.UNINSTALL_COMMAND_NAME, pluginName, projectData);
let showMessage = true;
const action = async (modulesDestinationPath: string, platform: string, platformData: IPlatformData): Promise<void> => {
shelljs.rm("-rf", path.join(modulesDestinationPath, pluginName));
this.$logger.info(`Successfully removed plugin ${pluginName} for ${platform}.`);
showMessage = false;
};
await this.executeForAllInstalledPlatforms(action, projectData);
if (showMessage) {
this.$logger.info(`Successfully removed plugin ${pluginName}`);
}
}
public addToPackageJson(plugin: string, version: string, isDev: boolean, projectDir: string) {
const packageJsonPath = this.getPackageJsonFilePath(projectDir);
let packageJsonContent = this.$fs.readJson(packageJsonPath);
const collectionKey = isDev ? "devDependencies" : "dependencies";
const oppositeCollectionKey = isDev ? "dependencies" : "devDependencies";
if (packageJsonContent[oppositeCollectionKey] && packageJsonContent[oppositeCollectionKey][plugin]) {
const result = this.removeDependencyFromPackageJsonContent(plugin, packageJsonContent);
packageJsonContent = result.packageJsonContent;
}
packageJsonContent[collectionKey] = packageJsonContent[collectionKey] || {};
packageJsonContent[collectionKey][plugin] = version;
this.$fs.writeJson(packageJsonPath, packageJsonContent);
}
public removeFromPackageJson(plugin: string, projectDir: string) {
const packageJsonPath = this.getPackageJsonFilePath(projectDir);
const packageJsonContent = this.$fs.readJson(packageJsonPath);
const result = this.removeDependencyFromPackageJsonContent(plugin, packageJsonContent);
if (result.hasModifiedPackageJson) {
this.$fs.writeJson(packageJsonPath, result.packageJsonContent);
}
}
public async preparePluginNativeCode({pluginData, platform, projectData}: IPreparePluginNativeCodeData): Promise<void> {
const platformData = this.$platformsDataService.getPlatformData(platform, projectData);
pluginData.pluginPlatformsFolderPath = (_platform: string) => path.join(pluginData.fullPath, "platforms", _platform.toLowerCase());
const pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(platform);
if (this.$fs.exists(pluginPlatformsFolderPath)) {
const pathToPluginsBuildFile = path.join(platformData.projectRoot, constants.PLUGINS_BUILD_DATA_FILENAME);
const allPluginsNativeHashes = this.getAllPluginsNativeHashes(pathToPluginsBuildFile);
const oldPluginNativeHashes = allPluginsNativeHashes[pluginData.name];
const currentPluginNativeHashes = await this.getPluginNativeHashes(pluginPlatformsFolderPath);
if (!oldPluginNativeHashes || this.$filesHashService.hasChangesInShasums(oldPluginNativeHashes, currentPluginNativeHashes)) {
await platformData.platformProjectService.preparePluginNativeCode(pluginData, projectData);
this.setPluginNativeHashes({
pathToPluginsBuildFile,
pluginData,
currentPluginNativeHashes,
allPluginsNativeHashes
});
}
}
}
public async ensureAllDependenciesAreInstalled(projectData: IProjectData): Promise<void> {
let installedDependencies = this.$fs.exists(this.getNodeModulesPath(projectData.projectDir)) ? this.$fs.readDirectory(this.getNodeModulesPath(projectData.projectDir)) : [];
// Scoped dependencies are not on the root of node_modules,
// so we have to list the contents of all directories, starting with @
// and add them to installed dependencies, so we can apply correct comparison against package.json's dependencies.
_(installedDependencies)
.filter(dependencyName => _.startsWith(dependencyName, "@"))
.each(scopedDependencyDir => {
const contents = this.$fs.readDirectory(path.join(this.getNodeModulesPath(projectData.projectDir), scopedDependencyDir));
installedDependencies = installedDependencies.concat(contents.map(dependencyName => `${scopedDependencyDir}/${dependencyName}`));
});
const packageJsonContent = this.$fs.readJson(this.getPackageJsonFilePath(projectData.projectDir));
const allDependencies = _.keys(packageJsonContent.dependencies).concat(_.keys(packageJsonContent.devDependencies));
const notInstalledDependencies = _.difference(allDependencies, installedDependencies);
if (this.$options.force || notInstalledDependencies.length) {
this.$logger.trace("Npm install will be called from CLI. Force option is: ", this.$options.force, " Not installed dependencies are: ", notInstalledDependencies);
await this.$packageManager.install(projectData.projectDir, projectData.projectDir, {
disableNpmInstall: this.$options.disableNpmInstall,
frameworkPath: this.$options.frameworkPath,
ignoreScripts: this.$options.ignoreScripts,
path: this.$options.path
});
}
}
public async getAllInstalledPlugins(projectData: IProjectData): Promise<IPluginData[]> {
const nodeModules = (await this.getAllInstalledModules(projectData)).map(nodeModuleData => this.convertToPluginData(nodeModuleData, projectData.projectDir));
return _.filter(nodeModules, nodeModuleData => nodeModuleData && nodeModuleData.isPlugin);
}
public getDependenciesFromPackageJson(projectDir: string): IPackageJsonDepedenciesResult {
const packageJson = this.$fs.readJson(this.getPackageJsonFilePath(projectDir));
const dependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.dependencies);
const devDependencies: IBasePluginData[] = this.getBasicPluginInformation(packageJson.devDependencies);
return {
dependencies,
devDependencies
};
}
public isNativeScriptPlugin(pluginPackageJsonPath: string): boolean {
const pluginPackageJsonContent = this.$fs.readJson(pluginPackageJsonPath);
return pluginPackageJsonContent && pluginPackageJsonContent.nativescript;
}
public convertToPluginData(cacheData: any, projectDir: string): IPluginData {
const pluginData: any = {};
pluginData.name = cacheData.name;
pluginData.version = cacheData.version;
pluginData.fullPath = cacheData.directory || path.dirname(this.getPackageJsonFilePathForModule(cacheData.name, projectDir));
pluginData.isPlugin = !!cacheData.nativescript || !!cacheData.moduleInfo;
pluginData.pluginPlatformsFolderPath = (platform: string) => path.join(pluginData.fullPath, "platforms", platform);
const data = cacheData.nativescript || cacheData.moduleInfo;
if (pluginData.isPlugin) {
pluginData.platformsDataService = data.platforms;
pluginData.pluginVariables = data.variables;
}
return pluginData;
}
private removeDependencyFromPackageJsonContent(dependency: string, packageJsonContent: Object): {hasModifiedPackageJson: boolean, packageJsonContent: Object} {
let hasModifiedPackageJson = false;
if (packageJsonContent.devDependencies && packageJsonContent.devDependencies[dependency]) {
delete packageJsonContent.devDependencies[dependency];
hasModifiedPackageJson = true;
}
if (packageJsonContent.dependencies && packageJsonContent.dependencies[dependency]) {
delete packageJsonContent.dependencies[dependency];
hasModifiedPackageJson = true;
}
return {
hasModifiedPackageJson,
packageJsonContent
};
}
private getBasicPluginInformation(dependencies: any): IBasePluginData[] {
return _.map(dependencies, (version: string, key: string) => ({
name: key,
version: version
}));
}
private getNodeModulesPath(projectDir: string): string {
return path.join(projectDir, "node_modules");
}
private getPackageJsonFilePath(projectDir: string): string {
return path.join(projectDir, "package.json");
}
private getPackageJsonFilePathForModule(moduleName: string, projectDir: string): string {
const pathToJsonFile = require.resolve(`${moduleName}/package.json`, {
paths: [projectDir]
});
return pathToJsonFile;
}
private getDependencies(projectDir: string): string[] {
const packageJsonFilePath = this.getPackageJsonFilePath(projectDir);
return _.keys(require(packageJsonFilePath).dependencies);
}
private getNodeModuleData(module: string, projectDir: string): INodeModuleData { // module can be modulePath or moduleName
if (!this.$fs.exists(module) || path.basename(module) !== "package.json") {
module = this.getPackageJsonFilePathForModule(module, projectDir);
}
const data = this.$fs.readJson(module);
return {
name: data.name,
version: data.version,
fullPath: path.dirname(module),
isPlugin: data.nativescript !== undefined,
moduleInfo: data.nativescript
};
}
private async ensure(projectData: IProjectData): Promise<void> {
await this.ensureAllDependenciesAreInstalled(projectData);
this.$fs.ensureDirectoryExists(this.getNodeModulesPath(projectData.projectDir));
}
private async getAllInstalledModules(projectData: IProjectData): Promise<INodeModuleData[]> {
await this.ensure(projectData);
const nodeModules = this.getDependencies(projectData.projectDir);
return _.map(nodeModules, nodeModuleName => this.getNodeModuleData(nodeModuleName, projectData.projectDir));
}
private async executeNpmCommand(npmCommandName: string, npmCommandArguments: string, projectData: IProjectData): Promise<string> {
if (npmCommandName === PluginsService.INSTALL_COMMAND_NAME) {
await this.$packageManager.install(npmCommandArguments, projectData.projectDir, this.npmInstallOptions);
} else if (npmCommandName === PluginsService.UNINSTALL_COMMAND_NAME) {
await this.$packageManager.uninstall(npmCommandArguments, PluginsService.NPM_CONFIG, projectData.projectDir);
}
return this.parseNpmCommandResult(npmCommandArguments);
}
private parseNpmCommandResult(npmCommandResult: string): string {
return npmCommandResult.split("@")[0]; // returns plugin name
}
private async executeForAllInstalledPlatforms(action: (_pluginDestinationPath: string, pl: string, _platformData: IPlatformData) => Promise<void>, projectData: IProjectData): Promise<void> {
const availablePlatforms = this.$mobileHelper.platformNames.map(p => p.toLowerCase());
for (const platform of availablePlatforms) {
const isPlatformInstalled = this.$fs.exists(path.join(projectData.platformsDir, platform.toLowerCase()));
if (isPlatformInstalled) {
const platformData = this.$platformsDataService.getPlatformData(platform.toLowerCase(), projectData);
const pluginDestinationPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME, "tns_modules");
await action(pluginDestinationPath, platform.toLowerCase(), platformData);
}
}
}
private getInstalledFrameworkVersion(platform: string, projectData: IProjectData): string {
const platformData = this.$platformsDataService.getPlatformData(platform, projectData);
const frameworkData = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName);
return frameworkData.version;
}
private isPluginDataValidForPlatform(pluginData: IPluginData, platform: string, projectData: IProjectData): boolean {
let isValid = true;
const installedFrameworkVersion = this.getInstalledFrameworkVersion(platform, projectData);
const pluginPlatformsData = pluginData.platformsDataService;
if (pluginPlatformsData) {
const versionRequiredByPlugin = (<any>pluginPlatformsData)[platform];
if (!versionRequiredByPlugin) {
this.$logger.warn(`${pluginData.name} is not supported for ${platform}.`);
isValid = false;
} else if (semver.gt(versionRequiredByPlugin, installedFrameworkVersion)) {
this.$logger.warn(`${pluginData.name} requires at least version ${versionRequiredByPlugin} of platform ${platform}. Currently installed version is ${installedFrameworkVersion}.`);
isValid = false;
}
}
return isValid;
}
private async getPluginNativeHashes(pluginPlatformsDir: string): Promise<IStringDictionary> {
let data: IStringDictionary = {};
if (this.$fs.exists(pluginPlatformsDir)) {
const pluginNativeDataFiles = this.$fs.enumerateFilesInDirectorySync(pluginPlatformsDir);
data = await this.$filesHashService.generateHashes(pluginNativeDataFiles);
}
return data;
}
private getAllPluginsNativeHashes(pathToPluginsBuildFile: string): IDictionary<IStringDictionary> {
let data: IDictionary<IStringDictionary> = {};
if (this.$fs.exists(pathToPluginsBuildFile)) {
data = this.$fs.readJson(pathToPluginsBuildFile);
}
return data;
}
private setPluginNativeHashes(opts: { pathToPluginsBuildFile: string, pluginData: IPluginData, currentPluginNativeHashes: IStringDictionary, allPluginsNativeHashes: IDictionary<IStringDictionary> }): void {
opts.allPluginsNativeHashes[opts.pluginData.name] = opts.currentPluginNativeHashes;
this.$fs.writeJson(opts.pathToPluginsBuildFile, opts.allPluginsNativeHashes);
}
}
$injector.register("pluginsService", PluginsService);