赞
踩
本文代码主要参考了字节开源库arco-cli的部分代码,代码是字节架构组的同学写的,学习一下大佬的代码。
这部分代码实现了一个用户交互的 GitHub 模板下载工具。首先你需要在github上创建一个项目,然后使用下面介绍的代码就可以用命令行拉取到本地,并解压了。
它使用 enquirer
库提示用户输入仓库的创建者、名称、分支、和目标目录,然后使用 downloadTemplate
函数下载模板,最后使用 fs-extra
库存储下载的文件。print
函数封装了日志记录的函数。
代码的具体实现如下:
引入依赖:`fs-extra`、`enquirer`、`downloadTemplate` 和 `print`。(print函数实现下面会有)
- import fs from 'fs-extra';
- import enquirer from 'enquirer';
- import downloadTemplate from './download';
- import print from './print';
定义接口 `IRepo` 和 `IAnswers`,用来描述仓库信息和用户输入的答案。
- type IRepo = {
- owner: string;
- name: string;
- branch: string;
- };
- type IAnswers = IRepo & {
- targetDir?: string;
- };
定义函数 `githubDownloadUrl`,用来构造仓库的下载 URL。
- function githubDownloadUrl(repo: IRepo) {
- return 'https://github.com/' + repo.owner + '/' + repo.name + '/archive/refs/heads/' + repo.branch + '.zip';
- }
定义一个问题数组,包含需要提示用户输入的问题及其验证逻辑。
questions 数组包含了四个问题对象,每个问题对象都有以下几个属性:- type:表示问题的类型,例如输入、选择、确认等。这里的问题都是输入类型。- name:表示问题产生的结果值的 key,例如当你在回答问题时输入的值会以 name 作为 key 存储在答案对象中。- message:表示问题的提示语,例如 "请输入仓库的创建者"。- default:表示问题的默认值,如果用户没有输入答案,则使用默认值。- validate:表示问题的验证函数,用来验证用户输入的答案是否合法。如果答案不合法,可以返回一个错误消息,提示用户重新输入。
这些问题将用于提示用户输入,并根据用户输入的答案计算下载模板的 URL 和存储文件的目录。
- const questions = [
- {
- type: 'input', // type为交互的类型
- name: 'owner', // 产生的值的key,比如你输入''
- message: '请输入仓库的创建者(example: "lio-mengxiang")', // 提示语
- default: 'lio-mengxiang',
- validate(val) {
- if (!val) {
- return '请输入文件名'; // 验证一下输入是否不为空
- }
- if (fs.accessSync(val, fs.constants.F_OK)) {
- return '文件已存在'; // 判断文件是否存在
- } else {
- return true;
- }
- },
- },
- {
- type: 'input',
- name: 'name',
- message: '请输入仓库名称(example: "react")',
- default: 'react-pnpm-monorepo-subTemplate',
- validate(val) {
- if (!val) {
- return '请输入仓库名'; // 验证一下输入是否不为空
- }
- return true;
- },
- },
- {
- type: 'input',
- name: 'branch',
- message: '请输入分支名(example: "main")',
- default: 'main',
- validate(val) {
- if (!val) {
- return '请输入分支名'; // 验证一下输入是否不为空
- }
- return true;
- },
- },
- {
- type: 'input',
- name: 'targetDir',
- message: '请输入放文件的目录(默认当前目录: "./")',
- default: './',
- },
- ];
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
使用 `enquirer.prompt` 方法提示用户输入,并处理用户输入的答案。如果输入有误,则输出错误信息并退出程序。
- enquirer
- .prompt(questions)
- .then((answers: IAnswers) => {
- // 获取用户输入值
- const owner = answers.owner;
- const name = answers.name;
- const branch = answers.branch;
- const targetDir = answers.targetDir;
- downloadTemplate({ url: githubDownloadUrl({ owner, name, branch }), targetDir });
- })
- .catch((err) => {
- print.error(err);
- process.exit(1);
- });
如果用户输入的答案合法,则使用 downloadTemplate
函数下载模板并使用 fs-extra
存储文件。
- import download from 'download';
- import compressing from 'compressing';
- import print from './print';
-
- /**
- * 下载远程项目模板的方法
- */
- export default function downloadTemplate({ url, targetDir = './' }: { url: string; targetDir?: string }): Promise<any> {
- print.info('download start, please wait...');
- // 通过get方法下载
- return download(url, targetDir)
- .on('end', () => {
- print.success('download done');
- })
- .then((stream) => {
- return compressing.zip.uncompress(stream, './');
- })
- .catch((err) => {
- print.error(err);
- });
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
例如,假设我们有一个数组 [1, 2, 3, 4, 5, 6],如果我们调用 group([1, 2, 3, 4, 5, 6], 2),那么这个函数会返回一个新的数组 [[1, 2], [3, 4], [5, 6]]。
- export function group(array: any[], subGroupLength: number) {
- let index = 0;
- const newArray = [];
-
- while (index < array.length) {
- newArray.push(array.slice(index, (index += subGroupLength)));
- }
- return newArray;
- }
这段代码定义了一个 execQuick
函数,它使用 spawn
子进程的方式执行一条命令。spawn
子进程的优点是比 exec
更高效,因为它不需要创建新的 shell 环境,并且不会因超出最大缓冲区的限制而导致错误。
execQuick
函数接受一条命令和一些选项作为参数,并返回一个包含命令执行结果的 Promise 对象。
如果用户指定了 time
选项,execQuick
会在执行完命令后打印出命令执行所花费的时间;
如果用户指定了 silent
选项,execQuick
会禁止打印出命令的标准输出和标准错误输出。
- import { spawn } from 'child_process';
- import print from './print';
-
- /**
- * spawn优于exec的点
- * 1是在于不用新建shell,减少性能开销
- * 2是没有maxbuffer的限制
- */
- export default async function execQuick(
- command: string,
- options: {
- cwd?: string;
- time?: boolean;
- silent?: boolean;
- } = {}
- ): Promise<{ pid: number; code: number; stdout: string; stderr: string }> {
- return new Promise((resolve) => {
- const silent = options.silent !== false;
- const begin = new Date().getTime();
- const result = {
- pid: null,
- code: null,
- stdout: '',
- stderr: '',
- };
-
- const { stdout, stderr, pid } = spawn(command, {
- cwd: options.cwd,
- shell: true,
- }).on('close', (code) => {
- if (options.time) {
- const end = new Date().getTime();
- const waste = ((end - begin) / 1000).toFixed(2);
- print.info(command, `Command executed in ${waste} ms.`);
- }
-
- if (code !== 0 && !silent) {
- print.error(command, 'Command executed failed');
- }
-
- result.code = code;
- resolve(result);
- });
-
- result.pid = pid;
-
- stdout.on('data', (data) => {
- const dataStr = data.toString();
- if (!silent) {
- print.info(dataStr);
- }
- result.stdout += dataStr;
- });
-
- stderr.on('data', (data) => {
- const dataStr = data.toString();
- if (!silent) {
- print.error(dataStr);
- }
- result.stderr += dataStr;
- });
- });
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这段代码定义了一个打印日志的函数,名为 log
。它使用了 chalk
库来设置日志的颜色。
log
函数接受任意数量的参数,并将它们打印到标准输出。它也定义了四个分别对应不同颜色的打印函数,分别是 log.info
、log.warn
、log.error
和 log.success
。
这些函数会把它们的参数以不同的颜色打印出来。例如,log.success('成功')
会把字符串 '成功'
以绿色打印出来。
此外,log
还定义了一个名为 log.divider
的函数,它可以打印一条分隔线,用于区分不同的日志。分隔线的颜色可以通过 level
参数来指定,默认为 'info'
。
- /**
- * 更改颜色
- * example chalk.green('成功') 文字显示绿色
- */
- import chalk from 'chalk';
-
- type ILevel = 'info' | 'warn' | 'success' | 'error';
-
- function print(color: string, ...args: string[]) {
- if (args.length > 1) {
- log(chalk[`bg${color.replace(/^\w/, (w) => w.toUpperCase())}`](` ${args[0]} `), chalk[color](args.slice(1)));
- } else {
- log(chalk[color](...args));
- }
- }
-
- function log(...args) {
- console.log(...args);
- }
-
- log.info = print.bind(null, 'gray');
- log.warn = print.bind(null, 'yellow');
- log.error = print.bind(null, 'red');
- log.success = print.bind(null, 'green');
- log.chalk = chalk;
-
- /**
- * Print divider
- * @param {'info' | 'warn' | 'success' | 'error'} level
- */
- log.divider = (level: ILevel = 'info') => {
- const logger = log[level] || log.info;
- logger('---------------------------------------------------------------------------------------');
- };
-
- export default log;
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这些函数用于检查 JavaScript 中的对象是否属于特定的类型。例如,函数 isArray() 可以用来检查传入的对象是否为数组类型。isObject() 函数可以用来检查对象是否为对象类型,isString() 函数可以用来检查对象是否为字符串类型,以此类推。
主要基于的是一下函数去做判断
const getType = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
这个函数也是大家从jquery代码里学来的,一直沿用到现在,也是极为推崇的判断类型的方法,因为它非常准确。
- const getType = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
-
- export function isArray(obj: any): obj is any[] {
- return getType(obj) === 'Array';
- }
-
- export function isObject(obj: any): obj is { [key: string]: any } {
- return getType(obj) === 'Object';
- }
-
- export function isString(obj: any): obj is string {
- return getType(obj) === 'String';
- }
-
- export function isNumber(obj: any): obj is number {
- return getType(obj) === 'Number' && obj === obj;
- }
-
- export function isRegExp(obj: any) {
- return getType(obj) === 'RegExp';
- }
-
- export function isFile(obj: any): obj is File {
- return getType(obj) === 'File';
- }
-
- export function isBlob(obj: any): obj is Blob {
- return getType(obj) === 'Blob';
- }
-
- export function isUndefined(obj: any): obj is undefined {
- return obj === undefined;
- }
-
- export function isFunction(obj: any): obj is (...args: any[]) => any {
- return typeof obj === 'function';
- }
-
- export function isEmptyObject(obj: any): boolean {
- return isObject(obj) && Object.keys(obj).length === 0;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这段代码实现了一个名为cs
的函数,该函数能够将一组字符串类型的参数合并成一个字符串,并返回合并后的字符串。这个函数可以接受多个参数,并且支持字符串、字符串数组、对象等多种参数类型。在合并字符串时,会自动去除重复的字符串,并将所有字符串用空格隔开。
例如,对于以下调用:
cs('a', 'b', ['c', 'd'], { e: true, f: false }, null, undefined);
会返回字符串:
'a b c d e'
该函数可以用来替代类似的库(例如classnames
),用于合并一组字符串并作为一个类名使用。
- import { isString, isArray, isObject } from './is';
-
- type ClassNamesArg = string | string[] | { [key: string]: any } | undefined | null | boolean;
-
- /**
- * 代替classnames库,样式合并的方法
- */
- export default function cs(...args: ClassNamesArg[]): string {
- const length = args.length;
- let classNames: string[] = [];
- for (let i = 0; i < length; i++) {
- const v = args[i];
- if (!v) {
- continue;
- }
- if (isString(v)) {
- classNames.push(v);
- } else if (isArray(v)) {
- classNames = classNames.concat(v);
- } else if (isObject(v)) {
- Object.keys(v).forEach((k) => {
- if (v[k]) {
- classNames.push(k);
- }
- });
- }
- }
- return [...new Set(classNames)].join(' ');
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
omit函数,它接受两个参数:一个对象和一个数组。函数会返回一个新对象,该对象为传入的对象的浅拷贝,并删除了数组中列出的所有属性。
例如,如果传入的对象为 { a: 1, b: 2, c: 3 },数组为 ['a', 'c'],则返回的对象为 { b: 2 }。
- /**
- * delete keys from object
- */
- export default function omit<T extends Record<string | number, any>, K extends keyof T>(
- obj: T,
- keys: Array<K | string> // string 为了某些没有声明的属性被omit
- ): Omit<T, K> {
- const clone = {
- ...obj,
- };
- keys.forEach((key) => {
- if ((key as K) in clone) {
- delete clone[key as K];
- }
- });
- return clone;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这个函数定义了一个 getProjectPath() 函数。它接受一个目录路径作为参数,并返回这个目录在项目中的绝对路径。如果没有提供目录路径,默认使用当前工作目录作为目录路径。
这个函数可以用来根据相对路径获取文件在项目中的绝对路径。
例如,如果工作目录为 /home/user/project,传入目录路径为 './src',则返回值为 '/home/user/project/src'。
- import path from 'path';
-
- /**
- * 获取项目文件,以命令输入的目录为根目录
- */
- export default function getProjectPath(dir = './'): string {
- return path.join(process.cwd(), dir);
- }
通过更改css变量达到更换主题的目的
- import { isObject } from './is';
-
- /**
- * 更换css变量的方法
- */
- export function setCssVariables(variables: Record<string, any>, root = document.body) {
- if (variables && isObject(variables)) {
- Object.keys(variables).forEach((themKey) => {
- root.style.setProperty(themKey, variables[themKey]);
- });
- }
- }
这个函数定义了一个 checkGitRemote() 函数。它首先会使用 getGitRootPath() 函数检测当前目录是否为 Git 仓库。
如果是,它会执行 git remote -v 命令,然后检查命令的输出中是否包含 push。如果包含,则打印空行;
如果不包含,则打印错误信息,并退出程序。如果检测到的当前目录不是 Git 仓库,则打印错误信息,并退出程序
- import execQuick from './execQuick';
- import getGitRootPath from './getGitRootPath';
- import print from './print';
-
- export default async function checkGitRemote() {
- if (getGitRootPath()) {
- const { code, stdout } = await execQuick('git remote -v');
- if (code === 0 && stdout.match('(push)')) {
- print();
- } else {
- print.error(['publish'], '在指定 git remote 前,您无法发布代码,请手动添加 git remote。');
- process.exit(1);
- }
- } else {
- print.error(['publish'], '没有检测到 Git 仓库。');
- process.exit(1);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这个函数定义了一个 compose() 函数,它接受一个包含一组中间件对象的数组作为参数。
每个中间件对象都有一个名称和一个函数。
compose() 函数会按照数组中的顺序执行每个中间件函数。每个中间件函数执行完毕后,会更新一个名为 middlewareData 的对象,该对象包含了每个中间件函数处理后的数据。
最终返回的 middlewareData 对象可以用来在多个中间件之间共享数据。
- /**
- * 异步函数组合,是否调用下一个函数,完全由中间件自己决定
- * @param middleware 中间件
- */
-
- type IMiddleware = {
- name: string;
- fn: ({ middlewareData, next }: { middlewareData: Record<string, any>; next: () => void }) => Promise<{ data: Record<string, any> }>;
- };
-
- export default function compose(middleware: IMiddleware[]) {
- let middlewareData: Record<string, any> = {};
- async function dispatch(index: number) {
- if (index === middleware.length) return;
- const { name, fn } = middleware[index];
- const { data } = await fn({
- middlewareData,
- next: () => {
- dispatch(++index);
- },
- });
- middlewareData = {
- ...middlewareData,
- [name]: {
- ...middlewareData[name],
- ...data,
- },
- };
- }
- dispatch(0);
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
我们封装了在命令行工具中常用ora这个库,ora 是一个 JavaScript 库,用于在命令行中显示 loading 指示器。
它可以用来提示用户在执行异步操作时的进度和结果。例如,可以使用 ora 库在执行某个异步任务时显示一个转圈圈的 loading 指示器,并在任务完成后显示成功或失败信息。
接着看我们封装的函数,如果函数执行成功,则 loading 指示器会显示成功信息,并将函数的返回值作为 Promise 的成功值;
如果函数执行失败,则 loading 指示器会显示失败信息,并将函数抛出的错误作为 Promise 的失败值。这个函数可以用来提示用户在执行异步操作时的进度和结果。
- import ora from 'ora';
- import print from './print';
-
- export default function withOra(
- promiseFn: () => Promise<any>,
- { text, successText, failText, startText }: { text: string; successText: string; failText: string; startText?: string }
- ) {
- return new Promise((resolve, reject) => {
- const spinner = ora(text).start();
- startText && print.info(startText);
-
- promiseFn()
- .then((result) => {
- spinner.succeed(`✅ ${successText}`);
- resolve(result);
- })
- .catch((err) => {
- spinner.fail(`❎ ${failText}`);
- reject(err);
- });
- });
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
arco-cli:https://github.com/arco-design/arco-cli
作者: 孟祥_成都
https://juejin.cn/post/7176935575302668346
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。