Skip to content

Commit 4e227a4

Browse files
committed
refactor(@142vip/utils): 代码改造,简化类型声明,调整工具核心工具方法
1 parent 140d1c6 commit 4e227a4

File tree

18 files changed

+112
-213
lines changed

18 files changed

+112
-213
lines changed

packages/eslint-config/src/eslint.config.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
import type {
2-
OptionsConfig,
3-
TypedFlatConfigItem,
4-
} from '@antfu/eslint-config'
1+
import type { OptionsConfig, TypedFlatConfigItem } from '@antfu/eslint-config'
52
import { antfu } from '@antfu/eslint-config'
63

74
/**
@@ -37,11 +34,10 @@ type EslintConfigOptions = OptionsConfig & TypedFlatConfigItem
3734
/**
3835
* 定义Eslint配置
3936
* 参考:https://github.com/antfu/eslint-config
40-
* @param options
4137
*/
42-
export async function defineVipEslintConfig(
38+
export function defineVipEslintConfig(
4339
options: EslintConfigOptions = {},
44-
): Promise<any> {
40+
): any {
4541
return antfu(defaultEslintConfig, {
4642
...options,
4743
rules: {

packages/utils/src/constants.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import process from 'node:process'
1+
import { VipNodeJS } from './core'
2+
23
/**
34
* 一些地址信息
45
*/
@@ -51,7 +52,7 @@ export const OPEN_SOURCE_AUTHOR = {
5152
* @param baseName
5253
*/
5354
export function getDocSiteBase(baseName: string): '/' | `/${string}/` {
54-
const needProxy = process.env.NEED_PROXY ?? false
55+
const needProxy = VipNodeJS.getProcessEnv('NEED_PROXY') ?? false
5556

5657
return needProxy ? `/${baseName}/` : '/'
5758
}

packages/utils/src/core/docker.ts

Lines changed: 19 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import * as process from 'node:process'
2-
import { VipSymbols } from '../pkgs/color'
3-
import { commandStandardExecutor, execCommand } from './exec'
4-
import { VipLogger } from './logger'
1+
import {
2+
VipExecutor,
3+
VipLogger,
4+
VipNodeJS,
5+
VipSymbols,
6+
} from '@142vip/utils'
57

68
const vipLog = new VipLogger()
79

@@ -24,15 +26,15 @@ interface BuildImageDockerOptions extends DockerOptions {
2426
*/
2527
async function scriptExecutor(command: string) {
2628
try {
27-
const errorCode = await commandStandardExecutor(command)
29+
const errorCode = await VipExecutor.commandStandardExecutor(command)
2830
if (errorCode !== 0) {
2931
vipLog.error(`Error Code: ${errorCode}`, { startLabel: 'commandStandardExecutor' })
30-
process.exit(1)
32+
VipNodeJS.exitProcess(1)
3133
}
3234
}
3335
catch {
3436
// 构建镜像出错时,直接退出
35-
process.exit(1)
37+
VipNodeJS.exitProcess(1)
3638
}
3739
}
3840

@@ -41,7 +43,7 @@ async function scriptExecutor(command: string) {
4143
*/
4244
async function isExistImage(imageName: string) {
4345
const command = `docker images -q ${imageName}`
44-
const { code, stdout } = await execCommand(command)
46+
const { code, stdout } = await VipExecutor.execCommand(command)
4547
return code === 0 && stdout.trim() !== ''
4648
}
4749

@@ -50,23 +52,23 @@ async function isExistImage(imageName: string) {
5052
*/
5153
async function deleteImage(imageName: string) {
5254
const command = `docker rmi -f ${imageName}`
53-
return await execCommand(command)
55+
return await VipExecutor.execCommand(command)
5456
}
5557

5658
/**
5759
* 删除虚悬镜像
5860
*/
5961
async function deletePruneImages() {
6062
const command = 'docker image prune -f'
61-
return await execCommand(command)
63+
return await VipExecutor.execCommand(command)
6264
}
6365

6466
/**
6567
* 判断容器是否存在
6668
*/
6769
async function isExistContainer(containerName: string) {
6870
const command = `docker ps -aq -f name=${containerName}`
69-
const { code, stdout } = await execCommand(command)
71+
const { code, stdout } = await VipExecutor.execCommand(command)
7072

7173
return code === 0 && stdout.trim() !== ''
7274
}
@@ -76,15 +78,15 @@ async function isExistContainer(containerName: string) {
7678
*/
7779
async function deleteContainer(containerName: string) {
7880
const command = `docker rm -f ${containerName}`
79-
return await execCommand(command)
81+
return await VipExecutor.execCommand(command)
8082
}
8183

8284
/**
8385
* 是否安装docker
8486
*/
8587
async function isExistDocker(args?: DockerOptions) {
8688
const command = 'docker -v'
87-
const { code, stdout, stderr } = await execCommand(command)
89+
const { code, stdout, stderr } = await VipExecutor.execCommand(command)
8890

8991
// 打印日志
9092
if (args?.logger) {
@@ -106,7 +108,7 @@ async function isExistDocker(args?: DockerOptions) {
106108
*/
107109
async function isExistDockerCompose(args?: DockerOptions) {
108110
const command = 'docker-compose -v'
109-
const { code, stdout, stderr } = await execCommand(command)
111+
const { code, stdout, stderr } = await VipExecutor.execCommand(command)
110112

111113
// 打印日志
112114
if (args?.logger) {
@@ -196,33 +198,19 @@ interface CreateContainerOptions extends DockerOptions {
196198
async function createContainer(args: CreateContainerOptions) {
197199
if (args.networkName && !args.ip) {
198200
console.log('只指定ip,没有指定容器局域网')
199-
process.exit(1)
201+
VipNodeJS.exitProcess(1)
200202
}
201203
// 支持自定义网络
202204
const networkParams = args.networkName && args.ip ? `--network ${args.networkName} --ip` : ''
203205

204206
const command = `docker run -d --name ${args.containerName} --restart=unless-stopped ${networkParams} ${args.imageName}`
205-
await commandStandardExecutor(command)
206-
}
207-
208-
export interface IVipDocker {
209-
isExistDocker: typeof isExistDocker
210-
isExistDockerCompose: typeof isExistDockerCompose
211-
isExistImage: typeof isExistImage
212-
isExistContainer: typeof isExistContainer
213-
deleteImage: typeof deleteImage
214-
deletePruneImages: typeof deletePruneImages
215-
deleteContainer: typeof deleteContainer
216-
pushImage: typeof pushImage
217-
buildImage: typeof buildImage
218-
createContainer: typeof createContainer
219-
scriptExecutor: typeof scriptExecutor
207+
await VipExecutor.commandStandardExecutor(command)
220208
}
221209

222210
/**
223211
* docker工具
224212
*/
225-
export const VipDocker: IVipDocker = {
213+
export const VipDocker = {
226214
isExistDocker,
227215
isExistDockerCompose,
228216
isExistImage,

packages/utils/src/core/exec.ts

Lines changed: 62 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import * as childProcess from 'node:child_process'
22
import { Buffer } from 'node:buffer'
3-
import * as process from 'node:process'
43
import { execSync } from 'node:child_process'
4+
import { VipColor, VipConsole, VipLogger, VipNodeJS } from '@142vip/utils'
5+
import { name, version } from '../../package.json'
56

67
type Command = string | string[]
78

@@ -13,35 +14,23 @@ export interface CmdResult {
1314
cmd: string
1415
}
1516

16-
export interface FailedExec extends CmdResult {
17-
error: Error
18-
}
19-
20-
export interface SuccessfulExec extends CmdResult {
21-
code: number | null
22-
}
23-
2417
/**
2518
* 同步执行命令,并返回结果
26-
* @param cmd
27-
* @param opts
2819
*/
29-
export async function execCommand(
20+
async function execCommand(
3021
cmd: Command,
3122
opts?: Omit<childProcess.SpawnOptionsWithoutStdio, 'stdio' | 'cwd'>,
3223
): Promise<CmdResult> {
3324
const executable = Array.isArray(cmd) ? cmd.join(';') : cmd
3425
const options: childProcess.SpawnOptionsWithoutStdio = {
3526
...opts,
3627
stdio: 'pipe',
37-
cwd: process.cwd(),
28+
cwd: VipNodeJS.getProcessCwd(),
3829
}
3930

40-
const { platform } = process
41-
4231
try {
43-
const cmd = platform === 'win32' ? 'cmd' : 'sh'
44-
const arg = platform === 'win32' ? '/C' : '-c'
32+
const cmd = VipNodeJS.getProcessPlatform() === 'win32' ? 'cmd' : 'sh'
33+
const arg = VipNodeJS.getProcessPlatform() === 'win32' ? '/C' : '-c'
4534
const child = childProcess.spawn(cmd, [arg, executable], options)
4635

4736
return new Promise((resolve) => {
@@ -83,29 +72,28 @@ export async function execCommand(
8372
* 标准Linux命令执行器
8473
* - 支持打印结果
8574
* - 异步
86-
* @param cmd
8775
*/
88-
export function commandStandardExecutor(cmd: Command) {
76+
function commandStandardExecutor(cmd: Command) {
8977
const executable = Array.isArray(cmd) ? cmd.join('&&') : cmd
9078
const options: childProcess.SpawnOptionsWithoutStdio = {
9179
stdio: 'pipe',
92-
cwd: process.cwd(),
80+
cwd: VipNodeJS.getProcessCwd(),
9381
}
9482

9583
return new Promise((resolve, reject) => {
96-
const cmd = process.platform === 'win32' ? 'cmd' : 'sh'
97-
const arg = process.platform === 'win32' ? '/C' : '-c'
84+
const cmd = VipNodeJS.getProcessPlatform() === 'win32' ? 'cmd' : 'sh'
85+
const arg = VipNodeJS.getProcessPlatform() === 'win32' ? '/C' : '-c'
9886
const child = childProcess.spawn(cmd, [arg, executable], options)
9987

10088
child.stdout.on('data', (data: string) => {
10189
if (Buffer.isBuffer(data)) {
102-
console.log(data.toString())
90+
VipConsole.log(data.toString())
10391
}
10492
})
10593

10694
child.stderr.on('data', (data) => {
10795
if (Buffer.isBuffer(data)) {
108-
console.log(data.toString())
96+
VipConsole.log(data.toString())
10997
}
11098
})
11199

@@ -125,6 +113,56 @@ function execCommandSync(cmd: string, cwd?: string): string {
125113
return execSync(cmd, { encoding: 'utf8', cwd }).trim()
126114
}
127115

116+
export interface ShellCommand {
117+
command: string
118+
description?: string
119+
}
120+
121+
/**
122+
* 脚本执行器,执行shell命令
123+
*/
124+
async function execShell(commands: ShellCommand[] | string | ShellCommand) {
125+
// 全局日志
126+
const vipLog = VipLogger.getInstance()
127+
128+
const projectName = VipColor.greenBright(`[${name}@${version}]`)
129+
130+
let runCommands: ShellCommand[] = []
131+
if (typeof commands === 'string') {
132+
runCommands.push({
133+
command: commands,
134+
})
135+
}
136+
137+
if (typeof commands === 'object') {
138+
// 批量执行
139+
if (Array.isArray(commands)) {
140+
runCommands = commands
141+
}
142+
else {
143+
runCommands.push(commands)
144+
}
145+
}
146+
147+
// 批量执行
148+
for (const { command, description = '脚本' } of runCommands) {
149+
// 脚本命令打印
150+
vipLog.log(`【${description}${command}`, {
151+
startLabel: `${projectName}执行的命令:`,
152+
endLabel: '',
153+
})
154+
155+
// 同步执行,标准命令执行器
156+
await execCommand(command)
157+
}
158+
}
159+
160+
/**
161+
* 执行器
162+
*/
128163
export const VipExecutor = {
129164
execCommandSync,
165+
execCommand,
166+
execShell,
167+
commandStandardExecutor,
130168
}

packages/utils/src/core/git.ts

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { VipSemver } from '../pkgs'
2-
import { VipExecutor } from './exec'
1+
import { VipExecutor, VipSemver } from '@142vip/utils'
32

43
/**
54
* Git提交信息
@@ -122,21 +121,7 @@ function execPush(args: string[]): void {
122121
VipExecutor.execCommandSync(`git push ${args.join(' ')}`)
123122
}
124123

125-
export interface IVipGit {
126-
getRecentCommit: typeof getRecentCommit
127-
getFirstCommitHash: typeof getFirstCommitHash
128-
getGitHubRepo: typeof getGitHubRepo
129-
getCurrentBranch: typeof getCurrentBranch
130-
isRepoShallow: typeof isRepoShallow
131-
getTags: typeof getTags
132-
getLastMatchingTag: typeof getLastMatchingTag
133-
isPrerelease: typeof isPrerelease
134-
execCommit: typeof execCommit
135-
execTag: typeof execTag
136-
execPush: typeof execPush
137-
}
138-
139-
export const VipGit: IVipGit = {
124+
export const VipGit = {
140125
getRecentCommit,
141126
getFirstCommitHash,
142127
getGitHubRepo,

packages/utils/src/core/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,4 @@ export * from './logger'
33
export * from './exec'
44
export * from './git'
55
export * from './docker'
6-
export * from './shell'
76
export * from './package-json'

packages/utils/src/core/logger.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { VipColor } from '../pkgs/color'
1+
import { VipColor } from '@142vip/utils'
22

33
export interface LoggerOptions {
44
startLabel?: string
@@ -41,3 +41,5 @@ export class VipLogger {
4141
console.error(text)
4242
}
4343
}
44+
45+
export const vipLogger = new VipLogger()

packages/utils/src/core/nodejs.ts

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -102,28 +102,7 @@ async function writeFileByUTF8(filePath: PathLike | FileHandle, data:
102102
return promises.writeFile(filePath, data, 'utf-8')
103103
}
104104

105-
export interface IVipNodeJS {
106-
// process
107-
getProcessFirstArgv: typeof getProcessFirstArgv
108-
getProcessArgv: typeof getProcessArgv
109-
getCPUArch: typeof getCPUArch
110-
setProcessEnv: typeof setProcessEnv
111-
getProcessEnv: typeof getProcessEnv
112-
getProcessPlatform: typeof getProcessPlatform
113-
getProcessCwd: typeof getProcessCwd
114-
getProcessVersions: typeof getProcessVersions
115-
exitProcess: typeof exitProcess
116-
117-
// fs
118-
exitPath: typeof exitPath
119-
readFileToStrByUTF8: typeof readFileToStrByUTF8
120-
writeFileByUTF8: typeof writeFileByUTF8
121-
122-
// path
123-
pathJoin: typeof pathJoin
124-
}
125-
126-
export const VipNodeJS: IVipNodeJS = {
105+
export const VipNodeJS = {
127106
getProcessFirstArgv,
128107
getProcessArgv,
129108
getCPUArch,

0 commit comments

Comments
 (0)