|
- import { cp } from 'fs/promises';
- import { Argv } from 'yargs';
- import { useInternalPath } from '../mixins/internal-path';
- import { CommandError } from '../utils/error';
-
- export enum InitReturnCode {
- SUCCESS = 0,
- COULD_NOT_COPY_FILES = -2,
- COULD_NOT_INSTALL_DEPENDENCIES = -3,
- }
-
- const copyFiles = async () => {
- try {
- const srcPath = await useInternalPath('src', 'next');
- const destPath = await useInternalPath('.amanuensis', 'next');
- await cp(srcPath, destPath, { recursive: true });
- } catch (errRaw) {
- const err = errRaw as NodeJS.ErrnoException;
- throw new CommandError(
- InitReturnCode.COULD_NOT_COPY_FILES,
- `Could not copy files: ${err.message}`,
- );
- }
- };
-
- interface PackageManager {
- name: string;
- testCmd: [string, string[]];
- installCmd: [string, string[]];
- }
-
- const packageManagers: PackageManager[] = [
- {
- name: 'pnpm',
- testCmd: ['pnpm', ['--version']],
- installCmd: ['pnpm', ['install', '--ignore-workspace']],
- },
- {
- name: 'yarn',
- testCmd: ['yarn', ['--version']],
- installCmd: ['yarn', ['install']],
- },
- {
- name: 'npm',
- testCmd: ['npm', ['--version']],
- installCmd: ['npm', ['install']],
- },
- ];
-
- const installDependencies = async () => {
- const { execa } = await import('execa');
-
- const selectedPackageManagerIndex = await packageManagers.reduce(
- async (prevPmPromise, pkgm, i) => {
- const prevPm = await prevPmPromise;
- const { testCmd } = pkgm;
- const testPm = await execa(...testCmd);
- if (testPm.exitCode === 0 && prevPm === -1) {
- return i;
- }
- return prevPm;
- },
- Promise.resolve(-1),
- );
-
- if (selectedPackageManagerIndex < 0) {
- process.stderr.write('No package manager found\n');
- process.exit(-1);
- }
-
- const { [selectedPackageManagerIndex]: selectedPackageManager } = packageManagers;
- const cwd = await useInternalPath('.amanuensis', 'next');
- process.stdout.write(`In path: ${cwd}\n`);
- process.stdout.write(`Installing dependencies with ${selectedPackageManager.name}\n`);
- const result = await execa(
- selectedPackageManager.installCmd[0],
- selectedPackageManager.installCmd[1],
- { cwd },
- );
-
- if (result.exitCode !== 0) {
- throw new CommandError(InitReturnCode.COULD_NOT_INSTALL_DEPENDENCIES, 'Could not install dependencies');
- }
- };
-
- export const description = 'Initialize a new Amanuensis project' as const;
-
- export const builder = (yargsBuilder: Argv) => yargsBuilder;
-
- const init = async () => {
- try {
- await copyFiles();
- await installDependencies();
- } catch (errRaw) {
- const err = errRaw as CommandError;
- process.stderr.write(`${err.message}\n`);
- return err.exitCode;
- }
- return InitReturnCode.SUCCESS;
- };
-
- export default init;
|