|
| 1 | +import pico from 'picocolors'; |
| 2 | +import prompts from 'prompts'; |
| 3 | + |
| 4 | +import { ChildCommand, createChildCommand, formatChildCommand, spawnChildCommand } from './childCommands'; |
| 5 | +import { logError, logInfo, logSuccess, logWarning } from './logs'; |
| 6 | +import { getPackageJsonDependencies } from './packageJson'; |
| 7 | +import { getPackageManager } from './packageManager'; |
| 8 | +import { PROMPT_OPTIONS } from './prompts'; |
| 9 | + |
| 10 | +export async function getPackageManagerInstallCommand( |
| 11 | + packages: string[], |
| 12 | + options: string[] = [], |
| 13 | +): Promise<ChildCommand> { |
| 14 | + const packageManager = await getPackageManager(); |
| 15 | + const args = [packageManager === 'yarn' ? 'add' : 'install', ...packages, ...options]; |
| 16 | + return createChildCommand(packageManager, args); |
| 17 | +} |
| 18 | + |
| 19 | +export async function installMissingDependencies(message: string, requiredDependencies: string[]): Promise<void> { |
| 20 | + if (requiredDependencies.length === 0) return; |
| 21 | + |
| 22 | + const installedDependencies = await getPackageJsonDependencies({ includeDev: true }); |
| 23 | + const missingDependencies = requiredDependencies.filter(dep => !installedDependencies.includes(dep)); |
| 24 | + if (missingDependencies.length === 0) return; |
| 25 | + |
| 26 | + await installDependencies(message, missingDependencies); |
| 27 | +} |
| 28 | + |
| 29 | +export async function installDependencies(message: string, dependencies: string[]): Promise<void> { |
| 30 | + if (dependencies.length === 0) return; |
| 31 | + const installCommand = await getPackageManagerInstallCommand(dependencies); |
| 32 | + |
| 33 | + logWarning(message); |
| 34 | + logWarning(`Install command: ${pico.yellow(formatChildCommand(installCommand))}`); |
| 35 | + |
| 36 | + const dependencyResult: { installDependencies: boolean } = await prompts( |
| 37 | + { initial: true, message: 'Install dependencies?', name: 'installDependencies', type: 'confirm' }, |
| 38 | + PROMPT_OPTIONS, |
| 39 | + ); |
| 40 | + if (!dependencyResult.installDependencies) { |
| 41 | + logWarning('Skipping installation. You can install manually later with:'); |
| 42 | + logWarning(pico.yellow(formatChildCommand(installCommand))); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + try { |
| 47 | + logInfo(`Installing`, dependencies); |
| 48 | + await spawnChildCommand(installCommand, { quiet: true }); |
| 49 | + logSuccess(`Dependencies installed successfully.`); |
| 50 | + } catch { |
| 51 | + logError(`Failed to install dependencies. Please try manually:`); |
| 52 | + logError(pico.yellow(formatChildCommand(installCommand))); |
| 53 | + } |
| 54 | +} |
0 commit comments