Skip to content

Commit

Permalink
feat: 添加create指令
Browse files Browse the repository at this point in the history
  • Loading branch information
xuasir committed Mar 6, 2021
1 parent 30eacf7 commit 1948c73
Show file tree
Hide file tree
Showing 22 changed files with 386 additions and 37 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"homepage": "https://github.com/xus-code/bundle-tools#readme",
"scripts": {
"test": "jest",
"copy:preset": "xus copy --src packages/preset-built-in/src/plugin/template --dest packages/preset-built-in/dist/plugin/template"
"copy:preset": "xus copy --src packages/preset-built-in/src/plugin/template --dest packages/preset-built-in/dist/plugin/template",
"copy:create": "xus copy --src packages/create-lib/src/template --dest packages/create-lib/dist/template"
},
"devDependencies": {
"@types/jest": "^26.0.20",
Expand Down
16 changes: 8 additions & 8 deletions packages/cli-shared/src/file/copyDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { mkdirSync, readdirSync, statSync, copyFileSync } from 'fs'
import { resolve } from 'path'

export function copy(src: string, dest: string) {
mkdirSync(dest, { recursive: true })
for (const file of readdirSync(src)) {
const srcPath = resolve(src, file)
const destPath = resolve(dest, file)
const stat = statSync(srcPath)
if (stat.isDirectory()) {
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(srcPath, destPath)
}
} else {
copyFileSync(src, dest)
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
{
"name": "@xus/preset-cmd-create",
"version": "0.1.2",
"name": "@xus/create-lib",
"version": "0.1.0",
"description": "xus cli cmd create",
"bin": {
"create-lib": "dist/cli.js",
"cxl": "dist/cli.js"
},
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"keywords": [
Expand All @@ -20,12 +24,13 @@
},
"scripts": {
"dev:create": "tsc --watch",
"build:create": "tsc"
"build:create": "tsc",
"update:temp": "node ./updateVersion.js"
},
"bugs": {
"url": "https://github.com/xus-code/bundle-tools/issues"
},
"dependencies": {
"@xus/cli": "^0.1.5"
}
}
}
15 changes: 15 additions & 0 deletions packages/create-lib/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node

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

async function main() {
await createTemp(args)
}

main().catch((e) => {
console.log(e)
process.exit(1)
})
108 changes: 108 additions & 0 deletions packages/create-lib/src/create.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import type { IPluginAPI, IArgs } from '@xus/cli'
import {
prompt,
emptyDir,
copy,
getPkgManager,
runCmd,
Spinner
} from '@xus/cli'
import { join } from 'path'
import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs'

const BuiltInTemp = ['ts-lib']
const FileMap: Record<string, string> = {
_eslintignore: '.eslintignore',
'_eslintrc.js': '.eslintrc.js',
_gitignore: '.gitignore',
'_prettierrc.js': '.prettierrc.js'
}
const spinner = new Spinner()

export async function createTemp(args: IArgs, api?: IPluginAPI) {
api?.logger.debug(`handle of project dir`)
let projectDir = args._.shift()
if (!projectDir) {
const { name } = await prompt<{ name: string }>({
type: 'input',
name: 'name',
message: `Project name:`,
initial: 'xus-project'
})
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 {
const files = readdirSync(root)
if (files.length > 0) {
const { yes } = await prompt<{ yes: boolean }>({
type: 'confirm',
name: 'yes',
initial: 'Y',
message:
`Target directory ${root} is not empty.\n` +
`Remove existing files and continue?`
})

if (yes) {
emptyDir(root)
} else {
return
}
}
}

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

if (temp) {
isvalidTemp = BuiltInTemp.includes(temp)
message = `${temp} isn't a valid template. Please choose:`
}

if (!temp || !isvalidTemp) {
const { t } = await prompt<{ t: string }>({
type: 'select',
name: 't',
message,
choices: BuiltInTemp
})
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) {
const to = join(root, FileMap[file] ? FileMap[file] : file)
const form = join(tempDir, file)
if (content) {
writeFileSync(to, content)
} else {
copy(form, to)
}
}
const files = readdirSync(tempDir)
for (const file of files) {
write(file)
}
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',
failed: 'Install deps failed'
})
}
22 changes: 22 additions & 0 deletions packages/create-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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)
}
)
}
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { helloWord } from '../src'

describe('test index ', () => {
test('test helloWord ', () => {
expect(helloWord()).toBe('hello-word')
})
})
2 changes: 2 additions & 0 deletions packages/create-lib/src/template/ts-lib/_eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
node_modules
3 changes: 3 additions & 0 deletions packages/create-lib/src/template/ts-lib/_eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: [require.resolve('@xus/eslint-config')]
}
104 changes: 104 additions & 0 deletions packages/create-lib/src/template/ts-lib/_gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
5 changes: 5 additions & 0 deletions packages/create-lib/src/template/ts-lib/_prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const prettier = require('@xus/eslint-config/prettier')

module.exports = {
...prettier
}
13 changes: 13 additions & 0 deletions packages/create-lib/src/template/ts-lib/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const path = require('path')

module.exports = {
preset: 'ts-jest',
rootDir: __dirname,
collectCoverage: true,
collectCoverageFrom: ['./src/**/**.ts'],
coverageDirectory: path.resolve(__dirname, 'coverage'),
coverageReporters: ['html', 'text'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
watchPathIgnorePatterns: ['node_modules'],
testMatch: ['./__test__/**/*spec.[jt]s?(x)']
}
41 changes: 41 additions & 0 deletions packages/create-lib/src/template/ts-lib/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "ts-lib-template",
"version": "1.0.0",
"description": "ts lib",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "xus lib",
"lint-fix": "xus lint",
"test": "jest",
"changelog": "xus changelog",
"release": "xus release"
},
"keywords": [
"ts",
"lib"
],
"author": "who am i",
"license": "MIT",
"gitHooks": {
"pre-commit": "lint-staged",
"commit-msg": "xus commit-lint"
},
"lint-staged": {
"*.{ts}": [
"lint-fix",
"prettier --parser=typescript --write"
]
},
"devDependencies": {
"@types/jest": "^26.0.20",
"@types/node": "^14.14.22",
"@xus/cli": "^0.1.3",
"@xus/eslint-config": "^0.1.2",
"jest": "^26.6.3",
"lint-staged": "^10.2.11",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3"
}
}
1 change: 1 addition & 0 deletions packages/create-lib/src/template/ts-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const helloWord = () => 'hello-word'

0 comments on commit 1948c73

Please sign in to comment.