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