core/src/npm/executor.ts

70 lines
1.9 KiB
TypeScript

import * as fs from 'fs-extra';
import * as path from 'path';
import { IEnvironment } from '../types/environment';
import { IProcessData, spawnProcess } from '../util/run';
export class NPMExecutor {
private installed: string[] = [];
private packageFile: string = path.join(this.environment.path, 'package.json');
constructor(private environment: IEnvironment, private coreModule: string) {}
public async init(): Promise<void> {
// Initialize npm environment
const c1 = await spawnProcess('npm', ['init', '-y'], this.environment);
if (c1.code > 0) {
throw new Error(c1.stderr.join('\n'));
}
// Install core module
const c2 = await spawnProcess('npm', ['install', this.coreModule], this.environment);
if (c2.code > 0) {
throw new Error(c2.stderr.join('\n'));
}
}
public async loadPackageFile(): Promise<void> {
if (!await fs.pathExists(this.packageFile)) {
await this.init();
}
const jsonData = await fs.readJson(this.packageFile);
if (!jsonData.dependencies) {
return;
}
this.installed = Object.keys(jsonData.dependencies);
}
public async installPackage(pkg: string): Promise<void> {
if (!await fs.pathExists(this.packageFile)) {
await this.init();
}
const pkgNoVersion = pkg.split('@')[0];
if (this.installed.indexOf(pkgNoVersion) !== -1) {
return;
}
const { code, stderr, stdout } = await spawnProcess('npm', ['install', pkg], this.environment);
if (code > 0) {
throw new Error(stderr.join('\n'));
}
await this.loadPackageFile();
}
public async uninstallPackage(pkg: string): Promise<void> {
if (!await fs.pathExists(this.packageFile)) {
await this.init();
}
const { code, stderr, stdout } = await spawnProcess('npm', ['remove', pkg], this.environment);
if (code > 0) {
throw new Error(stderr.join('\n'));
}
await this.loadPackageFile();
}
}