Skip to content

Commit

Permalink
fix: create-lib去除和cli的耦合
Browse files Browse the repository at this point in the history
  • Loading branch information
xuasir committed Mar 6, 2021
1 parent 7b6a213 commit 136420c
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 48 deletions.
11 changes: 8 additions & 3 deletions packages/create-lib/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@xus/create-lib",
"version": "0.1.1",
"version": "0.1.2",
"description": "xus cli cmd create",
"bin": {
"create-lib": "dist/cli.js",
Expand Down Expand Up @@ -31,6 +31,11 @@
"url": "https://github.com/xus-code/bundle-tools/issues"
},
"dependencies": {
"@xus/cli": "^0.1.6"
"chalk": "^4.1.0",
"enquirer": "^2.3.6",
"execa": "^5.0.0",
"log-symbols": "^4.0.0",
"ora": "^5.3.0",
"yargs-parser": "^20.2.6"
}
}
}
5 changes: 2 additions & 3 deletions packages/create-lib/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/usr/bin/env node

import { createTemp } from './create'
import { yParser } from '@xus/cli'
const rawArgs = process.argv.slice(2)
const args = yParser(rawArgs)
import yParser from 'yargs-parser'
const args = yParser(process.argv.slice(2))

async function main() {
await createTemp(args)
Expand Down
23 changes: 4 additions & 19 deletions packages/create-lib/src/create.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import type { IPluginAPI, IArgs } from '@xus/cli'
import {
prompt,
emptyDir,
copy,
getPkgManager,
runCmd,
Spinner
} from '@xus/cli'
import { prompt } from 'enquirer'
import { emptyDir, copy, getPkgManager, runCmd } from './utils'
import { Spinner } from './spinner'
import { join } from 'path'
import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs'

Expand All @@ -19,8 +13,7 @@ const FileMap: Record<string, string> = {
}
const spinner = new Spinner()

export async function createTemp(args: IArgs, api?: IPluginAPI) {
api?.logger.debug(`handle of project dir`)
export async function createTemp(args: { _: string[]; [key: string]: any }) {
let projectDir = args._.shift()
if (!projectDir) {
const { name } = await prompt<{ name: string }>({
Expand All @@ -31,10 +24,8 @@ export async function createTemp(args: IArgs, api?: IPluginAPI) {
})
projectDir = name
}
api?.logger.debug(projectDir)

const root = join(process.cwd(), projectDir)
api?.logger.debug(`create root ${root}`)
if (!existsSync(root)) {
mkdirSync(root, { recursive: true })
} else {
Expand All @@ -57,8 +48,6 @@ export async function createTemp(args: IArgs, api?: IPluginAPI) {
}
}

api?.logger.debug(`ready to copy`)
api?.logger.debug(`ensure template`)
let temp = args?.t || args?.template
let message = 'Select a template'
let isvalidTemp = false
Expand All @@ -77,9 +66,7 @@ export async function createTemp(args: IArgs, api?: IPluginAPI) {
})
temp = t
}
api?.logger.debug(temp)

api?.logger.debug(`copy file`)
spinner.start(`Create project start`)
const tempDir = join(__dirname, `./template/${temp}`)
function write(file: string, content?: string) {
Expand All @@ -98,8 +85,6 @@ export async function createTemp(args: IArgs, api?: IPluginAPI) {
spinner.succeed(`Create project succeed`)

const pkgManager = getPkgManager()
api?.logger.debug(`current pkgManager ${pkgManager}`)
api?.logger.debug(`install deps`)
await runCmd(pkgManager, pkgManager === 'yarn' ? [] : ['install'], {
start: 'Install deps start',
succeed: 'Install deps succeed',
Expand Down
23 changes: 1 addition & 22 deletions packages/create-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1 @@
import { createPlugin } from '@xus/cli'
import { createTemp } from './create'

export default createPlugin({
name: 'cmd:create',
apply(api) {
api.registerCommand(
'create',
{
desc: 'create template project',
usage: 'xus create [dir]',
options: {
'--template': 'point a template',
'-t': 'point a template short option'
}
},
async (args) => {
await createTemp(args, api)
}
)
}
})
export * from './create'
19 changes: 19 additions & 0 deletions packages/create-lib/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import chalk from 'chalk'

const INFO = chalk.black.bgBlue(' INFO ')
const WARN = chalk.black.bgHex('#faad14')(' WARN ')
const ERROR = chalk.black.bgRed(' ERROR ')
const SUCCESS = chalk.black.bgGreen(' SUCCESS ')

export const info = (msg: string) => {
console.log(INFO, msg)
}
export const wran = (msg: string) => {
console.log(WARN, msg)
}
export const error = (msg: string) => {
console.log(ERROR, msg)
}
export const success = (msg: string) => {
console.log(SUCCESS, msg)
}
35 changes: 35 additions & 0 deletions packages/create-lib/src/spinner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import ora from 'ora'
import chalk from 'chalk'
import logSymbols from 'log-symbols'

type OraIns = ora.Ora | null

export class Spinner {
private oraIns!: OraIns

start(msg: string) {
if (this.oraIns) {
this.oraIns.stop()
} else {
this.oraIns = ora()
}
this.oraIns.text = chalk.yellow(' ' + msg)
this.oraIns.start()
}

failed(text?: string) {
this.oraIns &&
this.oraIns.stopAndPersist({
symbol: logSymbols.error,
text: chalk.red(text || this.oraIns.text)
})
}

succeed(text?: string) {
this.oraIns &&
this.oraIns.stopAndPersist({
symbol: logSymbols.success,
text: chalk.green(text || this.oraIns.text)
})
}
}
75 changes: 75 additions & 0 deletions packages/create-lib/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import execa from 'execa'
import {
mkdirSync,
readdirSync,
statSync,
copyFileSync,
existsSync,
lstatSync,
rmdirSync,
unlinkSync
} from 'fs'
import { resolve } from 'path'
import { error } from './logger'
import { Spinner } from './spinner'

const spinner = new Spinner()

export function copy(src: string, dest: string) {
const stat = statSync(src)
if (stat.isDirectory()) {
mkdirSync(dest, { recursive: true })
for (const file of readdirSync(src)) {
const srcPath = resolve(src, file)
const destPath = resolve(dest, file)
copy(srcPath, destPath)
}
} else {
copyFileSync(src, dest)
}
}

export function emptyDir(dir: string) {
if (!existsSync(dir)) {
return
}
for (const file of readdirSync(dir)) {
const abs = resolve(dir, file)
if (lstatSync(abs).isDirectory()) {
emptyDir(abs)
rmdirSync(abs)
} else {
unlinkSync(abs)
}
}
}

export const getPkgManager = () =>
/yarn/.test(process.env?.npm_execpath || '') ? 'yarn' : 'npm'

export type IRunCmdMessage = {
start: string
succeed: string
failed: string
}

export function runCmd(
cmd: string,
args: string[],
message: IRunCmdMessage,
options?: execa.Options
): Promise<boolean> {
spinner.start(message.start)
return new Promise((resolve, reject) => {
execa(cmd, args, options)
.then(() => {
spinner.succeed(message.succeed)
resolve(true)
})
.catch((err: any) => {
spinner.failed(message.failed)
error(err)
reject(false)
})
})
}
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -13877,7 +13877,7 @@ yargs-parser@20.2.5, yargs-parser@^20.2.5:
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.5.tgz#5d37729146d3f894f39fc94b6796f5b239513186"
integrity sha512-jYRGS3zWy20NtDtK2kBgo/TlAoy5YUuhD9/LZ7z7W4j1Fdw2cqD0xEEclf8fxc8xjD6X5Qr+qQQwCEsP8iRiYg==

yargs-parser@20.x, yargs-parser@^20.2.2:
yargs-parser@20.x, yargs-parser@^20.2.2, yargs-parser@^20.2.6:
version "20.2.6"
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.6.tgz#69f920addf61aafc0b8b89002f5d66e28f2d8b20"
integrity sha512-AP1+fQIWSM/sMiET8fyayjx/J+JmTPt2Mr0FkrgqB4todtfa53sOsrSAcIrJRD5XS20bKUwaDIuMkWKCEiQLKA==
Expand Down

0 comments on commit 136420c

Please sign in to comment.