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