๐Ÿ“ฆ lencx / create-mpl

๐Ÿ“„ index.ts ยท 82 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82import chalk from 'chalk';
import minimist from 'minimist';

import pkgJSON from '../package.json';
import { mplPrompts, isEmpty, isExist } from './utils';

const argv = minimist(process.argv.slice(2));

const appTypes = [
  { title: 'Web App', value: 'web' },
  { title: 'Tauri', value: 'tauri' },
  { title: 'Mini Program', value: 'mini' },
  { title: 'WebAssembly', value: 'wasm' },
  { title: 'Extension', value: 'extension' },
  { title: 'Electron', value: 'electron' },
  // custom: mpl-template-*
  { title: 'GitHub Template', value: 'github' },
];

async function init() {
  let targetDir = argv._[0];
  let mplType = argv.type || argv.t;
  const defaultProjectName = !targetDir ? 'mpl-project' : targetDir;
  const hasType = appTypes.map(i => i.value).includes(mplType);
  let result: Record<string, string> = {};

  console.log('โšก๏ธ' + chalk.gray(`v${pkgJSON.version}`));

  try {
    result = await mplPrompts([
      {
        type: targetDir ? null : 'text',
        name: 'projectName',
        message: 'Project name:',
        initial: defaultProjectName,
        onState: (state) => (targetDir = state.value.trim() || defaultProjectName),
      },
      {
        type: () => (!isExist(targetDir) || isEmpty(targetDir)) ? null : 'confirm',
        name: 'overwrite',
        message: () => (
          targetDir === '.'
            ? 'Current directory'
            : `Target directory "${targetDir}"`) +
          ` is not empty. Remove existing files and continue?`,
      },
      {
        type: (_, { overwrite }: any = {}) => {
          if (overwrite === false) {
            throw new Error(chalk.red`โœ–` + ' Operation cancelled');
          }
          return null
        },
        name: 'overwriteChecker'
      },
      {
        type: hasType ? null : 'select',
        name: 'type',
        message: 'Select an application types:',
        initial: 0,
        choices: appTypes,
        onState: (state) => (mplType = state.value),
      },
    ])
  } catch(e) {
    console.error(e);
    return;
  }

  const { projectName, type } = result;
  const appName = projectName || targetDir;
  const appType = type || mplType;

  if (appTypes.map(i => i.value).includes(appType)) {
    require(`./mpl/${appType}`).default(appName);
  }
}

init()
  .catch((e) => {
    console.error(e);
  });