]>
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 | ||
9b474844 | 8 | async function installNpmPlugin (npmName: string, version?: string) { |
f023a19c | 9 | // Security check |
9b474844 | 10 | checkNpmPluginNameOrThrow(npmName) |
ad91e700 C |
11 | if (version) checkPluginVersionOrThrow(version) |
12 | ||
9b474844 | 13 | let toInstall = npmName |
ad91e700 | 14 | if (version) toInstall += `@${version}` |
f023a19c | 15 | |
09071200 C |
16 | const { stdout } = await execYarn('add ' + toInstall) |
17 | ||
18 | logger.debug('Added a yarn package.', { yarnStdout: stdout }) | |
f023a19c C |
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 | ||
09071200 | 51 | return execShell(`yarn ${command}`, { cwd: pluginDirectory }) |
f023a19c C |
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 | } |