|
| 1 | +import colors from 'colors'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import path from 'node:path'; |
| 4 | +import ora from 'ora'; |
| 5 | +import { detect, resolveCommand } from 'package-manager-detector'; |
| 6 | +import { CliError } from '../cli-error'; |
| 7 | +import { execSync } from '../utils/exec-utils'; |
| 8 | +import { STARTER_ZMODEL } from './templates'; |
| 9 | + |
| 10 | +/** |
| 11 | + * CLI action for getting information about installed ZenStack packages |
| 12 | + */ |
| 13 | +export async function run(projectPath: string) { |
| 14 | + const packages = [ |
| 15 | + { name: '@zenstackhq/cli', dev: true }, |
| 16 | + { name: '@zenstackhq/runtime', dev: false }, |
| 17 | + ]; |
| 18 | + let pm = await detect(); |
| 19 | + if (!pm) { |
| 20 | + pm = { agent: 'npm', name: 'npm' }; |
| 21 | + } |
| 22 | + |
| 23 | + console.log(colors.gray(`Using package manager: ${pm.agent}`)); |
| 24 | + |
| 25 | + for (const pkg of packages) { |
| 26 | + const resolved = resolveCommand(pm.agent, 'install', [ |
| 27 | + pkg.name, |
| 28 | + ...(pkg.dev ? [pm.agent === 'yarn' ? '--dev' : '--save-dev'] : []), |
| 29 | + ]); |
| 30 | + if (!resolved) { |
| 31 | + throw new CliError( |
| 32 | + `Unable to determine how to install package "${pkg.name}". Please install it manually.` |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + const spinner = ora(`Installing "${pkg.name}"`).start(); |
| 37 | + try { |
| 38 | + execSync(`${resolved.command} ${resolved.args.join(' ')}`, { |
| 39 | + cwd: projectPath, |
| 40 | + }); |
| 41 | + spinner.succeed(); |
| 42 | + } catch (e) { |
| 43 | + spinner.fail(); |
| 44 | + throw e; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const generationFolder = 'zenstack'; |
| 49 | + |
| 50 | + if (!fs.existsSync(path.join(projectPath, generationFolder))) { |
| 51 | + fs.mkdirSync(path.join(projectPath, generationFolder)); |
| 52 | + } |
| 53 | + |
| 54 | + if ( |
| 55 | + !fs.existsSync( |
| 56 | + path.join(projectPath, generationFolder, 'schema.zmodel') |
| 57 | + ) |
| 58 | + ) { |
| 59 | + fs.writeFileSync( |
| 60 | + path.join(projectPath, generationFolder, 'schema.zmodel'), |
| 61 | + STARTER_ZMODEL |
| 62 | + ); |
| 63 | + } else { |
| 64 | + console.log( |
| 65 | + colors.yellow( |
| 66 | + 'Schema file already exists. Skipping generation of sample.' |
| 67 | + ) |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + console.log(colors.green('ZenStack project initialized successfully!')); |
| 72 | + console.log( |
| 73 | + colors.gray( |
| 74 | + `See "${generationFolder}/schema.zmodel" for your database schema.` |
| 75 | + ) |
| 76 | + ); |
| 77 | + console.log( |
| 78 | + colors.gray( |
| 79 | + 'Run `zenstack generate` to compile the the schema into a TypeScript file.' |
| 80 | + ) |
| 81 | + ); |
| 82 | +} |
0 commit comments