@liuli-util/cli 3.15.0 → 3.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +100 -89
  2. package/LICENSE +21 -0
  3. package/dist/bin.js +96 -77
  4. package/dist/bin.js.map +3 -3
  5. package/dist/commands/deploy/DeployService.d.ts +52 -0
  6. package/dist/commands/deploy/DeployService.d.ts.map +1 -0
  7. package/dist/commands/deploy/deploy.d.ts +3 -0
  8. package/dist/commands/deploy/deploy.d.ts.map +1 -0
  9. package/dist/commands/deploy/index.d.ts +3 -0
  10. package/dist/commands/deploy/index.d.ts.map +1 -0
  11. package/dist/commands/deploy/util/FileLock.d.ts +14 -0
  12. package/dist/commands/deploy/util/FileLock.d.ts.map +1 -0
  13. package/dist/commands/deploy/util/PromiseUtil.d.ts +14 -0
  14. package/dist/commands/deploy/util/PromiseUtil.d.ts.map +1 -0
  15. package/dist/commands/deploy/util/createArchive.d.ts +10 -0
  16. package/dist/commands/deploy/util/createArchive.d.ts.map +1 -0
  17. package/dist/commands/deploy/util/execPromise.d.ts +4 -0
  18. package/dist/commands/deploy/util/execPromise.d.ts.map +1 -0
  19. package/dist/commands/deploy/util/wait.d.ts +9 -0
  20. package/dist/commands/deploy/util/wait.d.ts.map +1 -0
  21. package/dist/commands/esbuild/ESBuildProgram.d.ts.map +1 -1
  22. package/dist/index.esm.js +1 -1
  23. package/dist/index.esm.js.map +2 -2
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +2 -2
  26. package/dist/utils/nodeCacheDir.d.ts +2 -0
  27. package/dist/utils/nodeCacheDir.d.ts.map +1 -0
  28. package/package.json +73 -66
  29. package/src/bin.ts +3 -2
  30. package/src/commands/deploy/DeployService.ts +181 -0
  31. package/src/commands/deploy/__tests__/DeployService.test.ts +75 -0
  32. package/src/commands/deploy/__tests__/FileLock.test.ts +27 -0
  33. package/src/commands/deploy/__tests__/conf.test.ts +29 -0
  34. package/src/commands/deploy/__tests__/simpleGit.test.ts +54 -0
  35. package/src/commands/deploy/__tests__/util/deployGhPageWorker.ts +16 -0
  36. package/src/commands/deploy/deploy.ts +48 -0
  37. package/src/commands/deploy/index.ts +8 -0
  38. package/src/commands/deploy/util/FileLock.ts +31 -0
  39. package/src/commands/deploy/util/PromiseUtil.ts +34 -0
  40. package/src/commands/deploy/util/createArchive.ts +30 -0
  41. package/src/commands/deploy/util/execPromise.ts +13 -0
  42. package/src/commands/deploy/util/wait.ts +23 -0
  43. package/src/commands/esbuild/ESBuildProgram.ts +1 -1
  44. package/src/utils/__tests__/nodeCacheDir.test.ts +6 -0
  45. package/src/utils/nodeCacheDir.ts +54 -0
@@ -0,0 +1,75 @@
1
+ import * as path from 'path'
2
+ import { mkdirp, remove, writeFile } from 'fs-extra'
3
+ import { GhPagesDeployService, SftpDeployOptions, SftpDeployService } from '../DeployService'
4
+ import { execPromise } from '../util/execPromise'
5
+
6
+ const tempPath = path.resolve(__dirname, '.temp')
7
+ beforeAll(async () => {
8
+ const distPath = path.resolve(tempPath, 'dist')
9
+ await remove(tempPath)
10
+ await mkdirp(distPath)
11
+
12
+ await writeFile(
13
+ path.resolve(distPath, 'index.html'),
14
+ `<!DOCTYPE html>
15
+ <html lang="en">
16
+ <head>
17
+ <meta charset="UTF-8" />
18
+ <title>测试部署</title>
19
+ </head>
20
+ <body>
21
+ <h1>测试部署</h1>
22
+ </body>
23
+ </html>
24
+ `,
25
+ )
26
+ })
27
+
28
+ describe('测试 SftpDeployService', () => {
29
+ const options: SftpDeployOptions = {
30
+ cwd: tempPath,
31
+ dest: 'dist',
32
+ remote: '/home/pinefield/apps/test',
33
+ sshConfig: {
34
+ host: '10.8.2.4',
35
+ username: 'pinefield',
36
+ },
37
+ }
38
+ it('基本示例', async () => {
39
+ const sftpDeployService = new SftpDeployService(options)
40
+ await sftpDeployService.deploy()
41
+ })
42
+ describe('测试校验', () => {
43
+ it('正确情况', () => {
44
+ const [isValid] = new SftpDeployService(options).validate()
45
+ expect(isValid).toBeTruthy()
46
+ })
47
+ it('缺少字段', () => {
48
+ const [isValid, errorText] = new SftpDeployService({
49
+ cwd: tempPath,
50
+ } as SftpDeployOptions).validate()
51
+ expect(isValid).toBeFalsy()
52
+ console.log(errorText)
53
+ })
54
+ })
55
+ })
56
+
57
+ describe('测试 GhPagesDeployService', () => {
58
+ const ghPagesDeployService = new GhPagesDeployService({
59
+ cwd: tempPath,
60
+ dest: 'dist',
61
+ remote: 'examples/test-app',
62
+ })
63
+ it('基本示例', async () => {
64
+ await ghPagesDeployService.deploy().on('process', (title) => console.log(title))
65
+ }, 10_000)
66
+ //TODO 无法使用单元测试
67
+ it.skip('并发推送', async () => {
68
+ const scriptPath = path.resolve(__dirname, './util/deployGhPageWorker.ts').replace(/\\/g, '/')
69
+ await Promise.all(
70
+ [1, 2].map(async () => {
71
+ await execPromise(`esno ${scriptPath}`)
72
+ }),
73
+ )
74
+ }, 10_000)
75
+ })
@@ -0,0 +1,27 @@
1
+ import * as path from 'path'
2
+ import { FileLock } from '../util/FileLock'
3
+ import { AsyncArray } from '../../../utils'
4
+ import { wait } from '../util/wait'
5
+
6
+ describe('测试文件锁', () => {
7
+ const tempPath = path.resolve(__dirname, '.temp/test.lock')
8
+ it('基本示例', async () => {
9
+ const fileLock = new FileLock(tempPath)
10
+ expect(await fileLock.lock()).toBeTruthy()
11
+ expect(await fileLock.lock()).toBeFalsy()
12
+ await fileLock.unlock()
13
+ expect(await fileLock.lock()).toBeTruthy()
14
+ await fileLock.unlock()
15
+ })
16
+ it('测试并发调用', async () => {
17
+ const start = Date.now()
18
+ await AsyncArray.forEach(Array(10).fill(0), async () => {
19
+ const fileLock = new FileLock(tempPath)
20
+ await wait(() => fileLock.lock())
21
+ await wait(100)
22
+ await fileLock.unlock()
23
+ })
24
+ const time = Date.now() - start
25
+ expect(time).toBeLessThan(3000)
26
+ })
27
+ })
@@ -0,0 +1,29 @@
1
+ import Conf from 'conf'
2
+ import { wait } from '../util/wait'
3
+ import { writeJson } from 'fs-extra'
4
+ import * as path from 'path'
5
+
6
+ describe('测试 conf', () => {
7
+ const conf = new Conf<{ lock: boolean }>({ projectName: '@liuli-util/test' })
8
+ beforeEach(() => {
9
+ conf.clear()
10
+ })
11
+ it('测试并发模式', async () => {
12
+ await Promise.all([
13
+ wait(() => conf.store.lock),
14
+ wait(1000).then(() => {
15
+ conf.set('lock', true)
16
+ }),
17
+ ])
18
+ expect(conf.store.lock).toBeTruthy()
19
+ })
20
+ it('测试直接修改文件', async () => {
21
+ await Promise.all([
22
+ wait(() => conf.store.lock),
23
+ wait(1000).then(async () => {
24
+ await writeJson(conf.path, { lock: true })
25
+ }),
26
+ ])
27
+ expect(conf.store.lock).toBeTruthy()
28
+ })
29
+ })
@@ -0,0 +1,54 @@
1
+ import simpleGit, { SimpleGit } from 'simple-git'
2
+ import * as path from 'path'
3
+ import { mkdirp, pathExists, remove } from 'fs-extra'
4
+ import * as os from 'os'
5
+
6
+ describe('测试 simple-git', () => {
7
+ async function getOriginRemote() {
8
+ const git = simpleGit()
9
+ const remotes = await git.getRemotes(true)
10
+ return remotes.find((item) => item.name === 'origin')
11
+ }
12
+ let git: SimpleGit
13
+ const tempPath = path.resolve(__dirname, '.temp')
14
+ beforeEach(async () => {
15
+ git = simpleGit()
16
+ await remove(tempPath)
17
+ await mkdirp(tempPath)
18
+ })
19
+ it('测试获取当前项目的远端地址', async () => {
20
+ const originRemote = await getOriginRemote()
21
+ console.log('git.getRemotes', originRemote)
22
+ expect(originRemote).not.toBeUndefined()
23
+ })
24
+ it('克隆项目', async () => {
25
+ const originRemote = (await getOriginRemote())!
26
+ console.log('获取当前项目远端配置: ', originRemote)
27
+ const originRepoName = originRemote.refs.fetch.replace(new RegExp('[/:]', 'g'), '_')
28
+ await git.clone(originRemote.refs.fetch, path.resolve(tempPath, originRepoName), { '--branch': 'gh-pages' })
29
+ }, 100_000)
30
+ it('测试 git status', async () => {
31
+ await git.add('-A')
32
+ const status = await git.status()
33
+ console.log('status: ', status.files)
34
+ })
35
+ })
36
+
37
+ describe.skip('测试真实场景', () => {
38
+ const gitPath = path.resolve(
39
+ os.homedir(),
40
+ './AppData/Local/liuli-cli/Cache/gh-pages/https___github.com_rxliuli_webos.git',
41
+ )
42
+ const git = simpleGit(gitPath)
43
+ it('测试获取提交状态', async () => {
44
+ const res = await git.status()
45
+ console.log(res)
46
+ })
47
+ it('测试获取更新', async () => {
48
+ const res = await git.pull()
49
+ console.log(res)
50
+ }, 100_000)
51
+ it('测试 git add -A', async () => {
52
+ await git.add('-A')
53
+ })
54
+ })
@@ -0,0 +1,16 @@
1
+ import { GhPagesDeployService } from '../../DeployService'
2
+ import * as path from 'path'
3
+
4
+ async function deployGhPages() {
5
+ const tempPath = path.resolve(__dirname, '../.temp/')
6
+ const ghPagesDeployService = new GhPagesDeployService({
7
+ cwd: tempPath,
8
+ dest: 'dist',
9
+ remote: 'examples/test-app',
10
+ })
11
+ const now = Date.now()
12
+ await ghPagesDeployService.deploy().on('process', (title) => console.log(`[${now}] ${title}`))
13
+ }
14
+
15
+ // noinspection JSIgnoredPromiseFromCall
16
+ deployGhPages()
@@ -0,0 +1,48 @@
1
+ import {
2
+ BaseDeployOptions,
3
+ DeployTypeEnum,
4
+ GhPagesDeployService,
5
+ IDeployService,
6
+ SftpDeployOptions,
7
+ SftpDeployService,
8
+ } from './DeployService'
9
+ import * as path from 'path'
10
+ import { pathExists, readJson } from 'fs-extra'
11
+
12
+ async function getOptions(cwd: string): Promise<BaseDeployOptions> {
13
+ const pkgJsonPath = path.resolve(cwd, 'package.json')
14
+ if (await pathExists(pkgJsonPath)) {
15
+ const config = (await readJson(pkgJsonPath)).deploy
16
+ if (!config) {
17
+ throw new Error('找不到配置')
18
+ }
19
+ return config
20
+ }
21
+ throw new Error('找不到配置')
22
+ }
23
+
24
+ export async function deploy(options: Omit<BaseDeployOptions, 'type'>): Promise<void> {
25
+ const deployOptions = await getOptions(options.cwd)
26
+ let service: IDeployService
27
+ const _options = {
28
+ ...options,
29
+ ...deployOptions,
30
+ } as unknown as SftpDeployOptions
31
+ switch (deployOptions.type) {
32
+ case DeployTypeEnum.Sftp:
33
+ service = new SftpDeployService(_options)
34
+ break
35
+ case DeployTypeEnum.GhPages:
36
+ service = new GhPagesDeployService(_options)
37
+ break
38
+ default:
39
+ throw new Error('未知的部署预设类型 ' + deployOptions.type)
40
+ }
41
+ const [isValidate, errorText] = service.validate()
42
+ if (!isValidate) {
43
+ throw new Error(errorText)
44
+ }
45
+ await service.deploy().on('process', (title) => {
46
+ console.info(title)
47
+ })
48
+ }
@@ -0,0 +1,8 @@
1
+ import { Command } from 'commander'
2
+ import { deploy } from './deploy'
3
+ import * as path from 'path'
4
+
5
+ export const deployCommand = new Command('deploy')
6
+ .description('部署项目到远端')
7
+ .option('--debug', '是否开启调试模式')
8
+ .action((options: { debug?: boolean }) => deploy({ cwd: path.resolve(), debug: !!options.debug }))
@@ -0,0 +1,31 @@
1
+ import { close, open, remove } from 'fs-extra'
2
+ import path from 'path'
3
+
4
+ export class FileLock {
5
+ constructor(private readonly lockFilePath: string) {}
6
+
7
+ private lockId?: number
8
+
9
+ /**
10
+ * 加锁
11
+ */
12
+ async lock(): Promise<boolean> {
13
+ try {
14
+ this.lockId = await open(path.resolve(this.lockFilePath), 'wx')
15
+ return true
16
+ } catch (e) {
17
+ return false
18
+ }
19
+ }
20
+
21
+ /**
22
+ * 解锁
23
+ */
24
+ async unlock(): Promise<void> {
25
+ if (!this.lockId) {
26
+ throw new Error('未加锁')
27
+ }
28
+ await remove(path.resolve(this.lockFilePath))
29
+ close(this.lockId)
30
+ }
31
+ }
@@ -0,0 +1,34 @@
1
+ import { ConditionalKeys, PromiseValue } from 'type-fest'
2
+
3
+ type VoidFunc = ((...args: any[]) => void) | undefined
4
+
5
+ export type EventExtPromise<T, E> = Promise<T> & {
6
+ on<K extends ConditionalKeys<E, VoidFunc>>(type: K, callback: E[K]): EventExtPromise<T, E>
7
+ }
8
+
9
+ export class PromiseUtil {
10
+ /**
11
+ * 创建一个支持 on* 事件的 Promise 实例
12
+ * @param executor
13
+ */
14
+ static wrapOnEvent<
15
+ F extends (events: any) => Promise<any>,
16
+ E extends Parameters<F>[0],
17
+ K extends ConditionalKeys<E, VoidFunc>,
18
+ >(executor: F): EventExtPromise<PromiseValue<ReturnType<F>>, E> {
19
+ const events: Partial<Pick<E, K>> = {}
20
+ const res = new Promise(async (resolve, reject) => {
21
+ await new Promise((resolve) => setTimeout(resolve, 0))
22
+ try {
23
+ resolve(await executor(events))
24
+ } catch (e) {
25
+ reject(e)
26
+ }
27
+ })
28
+ Reflect.set(res, 'on', (type: K, callback: E[K]) => {
29
+ events[type] = callback
30
+ return res
31
+ })
32
+ return res as any
33
+ }
34
+ }
@@ -0,0 +1,30 @@
1
+ import { create, CreateOptions } from 'tar'
2
+ import { promise } from 'glob-promise'
3
+ import * as path from 'path'
4
+
5
+ export type ArchiveOptions = {
6
+ // sourceDir 源目录,一般设置为 dist
7
+ sourceDir: string
8
+ // destPath 目标位置,可能是 <packageName>.jpl
9
+ destPath: string
10
+ }
11
+
12
+ /**
13
+ * 创建 jpl 压缩文件
14
+ * @param options
15
+ */
16
+ export async function createArchive(options: ArchiveOptions): Promise<void> {
17
+ const sourceDir = path.resolve(options.sourceDir)
18
+ const destPath = path.resolve(options.destPath)
19
+ const distFiles = (await promise(`${sourceDir}/**/*`, { nodir: true })).map((f) => f.substr(sourceDir.length + 1))
20
+ await create(
21
+ {
22
+ strict: true,
23
+ portable: true,
24
+ file: destPath,
25
+ cwd: sourceDir,
26
+ sync: true,
27
+ } as Partial<CreateOptions>,
28
+ distFiles,
29
+ )
30
+ }
@@ -0,0 +1,13 @@
1
+ import { exec, ExecOptions } from 'child_process'
2
+
3
+ export function execPromise(command: string, options?: ExecOptions): Promise<string | Buffer> {
4
+ return new Promise((resolve, reject) => {
5
+ exec(command, options, (error, stdout) => {
6
+ if (error) {
7
+ reject(error)
8
+ return
9
+ }
10
+ resolve(stdout)
11
+ })
12
+ })
13
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * 等待指定的时间/等待指定表达式成立
3
+ * 如果未指定等待条件则立刻执行
4
+ * 注: 此实现在 nodejs 10- 会存在宏任务与微任务的问题,切记 async-await 本质上还是 Promise 的语法糖,实际上并非真正的同步函数!!!即便在浏览器,也不要依赖于这种特性。
5
+ * @param param 等待时间/等待条件
6
+ * @returns Promise 对象
7
+ */
8
+ export function wait(param?: number | (() => boolean | Promise<boolean>)): Promise<void> {
9
+ return new Promise((resolve) => {
10
+ if (typeof param === 'number') {
11
+ setTimeout(resolve, param)
12
+ } else if (typeof param === 'function') {
13
+ const timer = setInterval(async () => {
14
+ if (await param()) {
15
+ clearInterval(timer)
16
+ resolve()
17
+ }
18
+ }, 100)
19
+ } else {
20
+ resolve()
21
+ }
22
+ })
23
+ }
@@ -31,7 +31,7 @@ export class ESBuildProgram {
31
31
  this.options.isWatch = isWatch
32
32
  }
33
33
 
34
- static readonly globalExternal = ['esbuild', 'pnpapi', 'ts-morph']
34
+ static readonly globalExternal = ['esbuild', 'pnpapi', 'ts-morph', 'ssh2']
35
35
 
36
36
  /**
37
37
  * 获取所有依赖
@@ -0,0 +1,6 @@
1
+ import { nodeCacheDir } from '../nodeCacheDir'
2
+
3
+ it('测试 nodeCacheDir', () => {
4
+ const res = nodeCacheDir('liuli-cli')
5
+ console.log(res)
6
+ })
@@ -0,0 +1,54 @@
1
+ /*
2
+ copy by https://github.com/LinusU/node-cachedir
3
+ */
4
+ import * as os from 'os'
5
+ import * as path from 'path'
6
+
7
+ function posix(id: string) {
8
+ const cacheHome = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache')
9
+ return path.join(cacheHome, id)
10
+ }
11
+
12
+ function darwin(id: string) {
13
+ return path.join(os.homedir(), 'Library', 'Caches', id)
14
+ }
15
+
16
+ function win32(id: string) {
17
+ const appData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')
18
+ return path.join(appData, id, 'Cache')
19
+ }
20
+
21
+ const implementation = (function () {
22
+ switch (os.platform()) {
23
+ case 'darwin':
24
+ return darwin
25
+ case 'win32':
26
+ return win32
27
+ case 'aix':
28
+ case 'android':
29
+ case 'freebsd':
30
+ case 'linux':
31
+ case 'netbsd':
32
+ case 'openbsd':
33
+ case 'sunos':
34
+ return posix
35
+ default:
36
+ console.error(
37
+ `(node:${
38
+ process.pid
39
+ }) [cachedir] Warning: the platform "${os.platform()}" is not currently supported by node-cachedir, falling back to "posix". Please file an issue with your platform here: https://github.com/LinusU/node-cachedir/issues/new`,
40
+ )
41
+ return posix
42
+ }
43
+ })()
44
+
45
+ export function nodeCacheDir(id: string): string {
46
+ if (id.length === 0) {
47
+ throw new Error('id cannot be empty')
48
+ }
49
+ if (/[^0-9a-zA-Z-]/.test(id)) {
50
+ throw new Error('id cannot contain special characters')
51
+ }
52
+
53
+ return implementation(id)
54
+ }