]>
Commit | Line | Data |
---|---|---|
1 | import { execShell } from '../../helpers/core-utils' | |
2 | import { logger } from '../../helpers/logger' | |
3 | import { isNpmPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins' | |
4 | import { CONFIG } from '../../initializers/config' | |
5 | import { outputJSON, pathExists } from 'fs-extra' | |
6 | import { join } from 'path' | |
7 | ||
8 | async function installNpmPlugin (npmName: string, version?: string) { | |
9 | // Security check | |
10 | checkNpmPluginNameOrThrow(npmName) | |
11 | if (version) checkPluginVersionOrThrow(version) | |
12 | ||
13 | let toInstall = npmName | |
14 | if (version) toInstall += `@${version}` | |
15 | ||
16 | const { stdout } = await execYarn('add ' + toInstall) | |
17 | ||
18 | logger.debug('Added a yarn package.', { yarnStdout: stdout }) | |
19 | } | |
20 | ||
21 | async function installNpmPluginFromDisk (path: string) { | |
22 | await execYarn('add file:' + path) | |
23 | } | |
24 | ||
25 | async function removeNpmPlugin (name: string) { | |
26 | checkNpmPluginNameOrThrow(name) | |
27 | ||
28 | await execYarn('remove ' + name) | |
29 | } | |
30 | ||
31 | // ############################################################################ | |
32 | ||
33 | export { | |
34 | installNpmPlugin, | |
35 | installNpmPluginFromDisk, | |
36 | removeNpmPlugin | |
37 | } | |
38 | ||
39 | // ############################################################################ | |
40 | ||
41 | async function execYarn (command: string) { | |
42 | try { | |
43 | const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR | |
44 | const pluginPackageJSON = join(pluginDirectory, 'package.json') | |
45 | ||
46 | // Create empty package.json file if needed | |
47 | if (!await pathExists(pluginPackageJSON)) { | |
48 | await outputJSON(pluginPackageJSON, {}) | |
49 | } | |
50 | ||
51 | return execShell(`yarn ${command}`, { cwd: pluginDirectory }) | |
52 | } catch (result) { | |
53 | logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr }) | |
54 | ||
55 | throw result.err | |
56 | } | |
57 | } | |
58 | ||
59 | function checkNpmPluginNameOrThrow (name: string) { | |
60 | if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install') | |
61 | } | |
62 | ||
63 | function checkPluginVersionOrThrow (name: string) { | |
64 | if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install') | |
65 | } |