repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
create-neat
github_2023
others
172
xun082
uaenaTzx
@@ -0,0 +1,76 @@ +import "./App.css"; + +function App() { + return ( + <div className="container"> + <header className="header"> + <h1 className="title">create-neat</h1> + <div className="description">
我理解应该在首页展示一个用户预设的组成,比如 React + webpack + xx 插件 通过 ejs 渲染 options 生成
create-neat
github_2023
typescript
162
xun082
uaenaTzx
@@ -196,11 +197,15 @@ class FileTree { * @param {string} [path=""] - 添加的文件的路径 */ addToTreeByFile(fileName: string, fileContent: string, path: string = "") { + const fileNameSplit = fileName.split("."); + // 文件名.分割的最后一位作为拓展名(babel.config.js、.browserslistrc、.eslintrc.js等等) + const fileExtension = fileNameSplit[fileNameSplit.length - 1] || ""; this.fileData.children.push({ path, children: [], type: "file", - describe: { fileName, fileContent, fileExtension: fileName.split(".")[1] || "" }, + // describe: { fileName, fileContent, fileExtension: fileName.split(".")[1] || "" },
可以删吧
create-neat
github_2023
typescript
162
xun082
uaenaTzx
@@ -92,12 +95,22 @@ async function projectSelect() { options: npmSource, })) as string; + // 选择插件配置文件生成位置 + responses.extraConfigFiles = (await select({ + message: "Where do you prefer placing config for Babel, ESLint, etc.?",
描述可以优化一下,etc. 加后面,表示额外的话,其实也不直观,最好是使用者一眼就能看出来
create-neat
github_2023
typescript
162
xun082
uaenaTzx
@@ -41,7 +41,7 @@ const defaultConfigTransforms = { yaml: [".postcssrc.yaml", ".postcssrc.yml"], }, }), - eslintConfig: new ConfigTransform({ + eslint: new ConfigTransform({
我理解这一块是不是能拆分出去? 1. 拆到每个插件的配置里,引用过来消费 2. 独立一个文件存放相关的 ConfigTransform 实例 你可以评估一下实现的成本,如果要很久,可以独立出去一个 issue
create-neat
github_2023
others
161
xun082
xun082
@@ -15,7 +15,33 @@ const buildToolConfigs = { }; }, vite: () => { - return {}; + return { + plugins: [ + { + name: "legacy", + params: { + targets: [
这种定义成一个常量这些吧,不要硬编码
create-neat
github_2023
typescript
161
xun082
xun082
@@ -92,3 +109,48 @@ export const mergeWebpackConfigAst = (rules, plugins, ast) => { }); return ast; }; + +/** + * 合并vite config ast + * 目前支持plugins中的第三方插件。例如:legacy + * 其余基础配置可配置到基础模版 + * @param plugins 本次合并的插件 + * @param ast 初始ast + */ +export const mergeViteConfigAst = (plugins, ast) => {
嵌套层级有点高了,看看能不能这样优化一下,然后再添加一下 ts 类型 ```ts export const mergeViteConfigAst = (plugins, ast) => { traverse(ast, { ImportDeclaration: (path) => { plugins.forEach((plugin) => { path.container.unshift( createImportDeclaration(plugin.import.name, plugin.import.from) ); }); }, enter(path) { if (path.isIdentifier({ name: "plugins" })) { const pluginConfigurations = plugins.map((plugin) => createPluginConfigurationAst(plugin) ); pluginConfigurations.forEach((configAst) => path.parent.value.elements.push(configAst) ); } }, }); return ast; }; function createPluginConfigurationAst(plugin) { const configObjects = Object.entries(plugin.params).map(([key, value]) => { const values = Array.isArray(value) ? value.map((v) => stringLiteral(v)) : [stringLiteral(value)]; return objectExpression([ createObjectProperty(key, arrayExpression(values)), ]); }); return createCallExpression(plugin.name, configObjects); } ```
create-neat
github_2023
typescript
159
xun082
xun082
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性 + */ +class FileTree { + private rootDirectory: string; //文件树的根目录路径 + private FileData: FileData; //文件树对象 + constructor(rootDirectory: string) { + (this.rootDirectory = rootDirectory), + (this.FileData = { + path: rootDirectory, + type: "dir", + children: [], + describe: { fileName: path.basename(rootDirectory) }, + }); + //初始化文件树对象 + this.FileData = FileTree.buildFileData(this.rootDirectory); + //根据process.env.isTs更改后缀 + process.env.isTs && this.changeFileExtensionToTs(); + } + /** + * + * @param src 文件树根路径 + * @returns 文件树对象 + * @description 根据目录构造文件数对象 + */ + static buildFileData(src: string) { + const file: FileData = { + path: src, + children: [], + describe: { fileName: path.basename(src) }, + }; + if (isDirectoryOrFile(src)) { + file.type = "dir"; + const entries = fs.readdirSync(src, { + withFileTypes: true, + }); + for (const entry of entries) { + const subTree = this.buildFileData(path.join(src, entry.name)); + file.children?.push(subTree); + } + } else { + const fileContent = fs.readFileSync(src, "utf8"); + file.type = "file"; + file.describe = { + fileName: path.basename(src).split(".")[0], + fileExtension: path.extname(src).slice(1), + fileContent, + }; + } + return file; + } + + /** + * + * @param file 文件数对象 + * @param handleFn 处理文件树对象的函数 + * @description 遍历树的一个方法,对每个fileData对象做一次handleFn处理 + */ + traverseTree(file: FileData, handleFn: (file: FileData) => any) { + handleFn(file); + if (file.children.length) { + file.children.forEach((subFile) => this.traverseTree(subFile, handleFn)); + } + } + /** + * @description 根据process.env.isTs来更改文件数对象的后缀属性 + */ + changeFileExtensionToTs() { + //更改后缀的处理函数 + function handleExt(file: FileData) { + if (file.type === "file") { + switch (file.describe?.fileExtension) { + case "js": + file.describe.fileExtension = "ts"; + break; + case "jsx": + file.describe.fileExtension = "tsx"; + break; + default: + break; + } + } + } + this.traverseTree(this.FileData, handleExt); + } + + /** + * + * @param src 目标文件路径 + * @param file 文件树对象 + * @param options ejs对应的options参数 + * @description 将单个文件树(type==='file')通过ejs渲染成文件,只渲染文件 + */ + async fileRender(src: string, file: FileData, options: any) { + const rendered = ejs.render(file.describe?.fileContent, options, {}); + await fs.writeFile(src, rendered); + } + + /** + * + * @param dest 目标目录路径 + * @param file 文件树对象 + * @param options ejs对应的Options参数 + * @description 将文件树渲染到指定目录下形成文件 + */ + async renderTemplates(dest: string, file: FileData = this.FileData, options: any = {}) {
优化一下这里 ```ts async renderTemplates(dest: string, file: FileData = this.fileData, options: any = {}) { await fs.ensureDir(dest); const promises = file.children.map(async subFile => { const destPath = path.join( dest, `${subFile.describe.fileName!}${subFile.type === "file" ? "." + subFile.describe.fileExtension : ""}`, ); if (subFile.type === "dir" && subFile.describe) { return this.renderTemplates(destPath, subFile, options); } else { return this.fileRender(destPath, subFile, options); } }); await Promise.all(promises); } ```
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹
jsdoc 的格式规范一下,首先函数作用放在最前面,也不需要 @description,可以参考存量代码的 jsdoc
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs";
和 jsdoc 间隔一下空格
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData {
这些地方都要空格一下
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性
可以说明一下这个类的属性
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性 + */ +class FileTree { + private rootDirectory: string; //文件树的根目录路径 + private fileData: FileData; //文件树对象 + constructor(rootDirectory: string) { + (this.rootDirectory = rootDirectory),
为啥要括号包裹呢,写法有点奇怪
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性 + */ +class FileTree { + private rootDirectory: string; //文件树的根目录路径 + private fileData: FileData; //文件树对象 + constructor(rootDirectory: string) { + (this.rootDirectory = rootDirectory), + (this.fileData = { + path: rootDirectory, + type: "dir", + children: [], + describe: { fileName: path.basename(rootDirectory) }, + }); + //初始化文件树对象 + this.fileData = FileTree.buildFileData(this.rootDirectory); + //根据process.env.isTs更改后缀
这个注释感觉不太对,注释的核心应该是说做了什么事情,比如:如果有 ts 插件则更改相关文件后缀
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性 + */ +class FileTree { + private rootDirectory: string; //文件树的根目录路径 + private fileData: FileData; //文件树对象 + constructor(rootDirectory: string) { + (this.rootDirectory = rootDirectory), + (this.fileData = { + path: rootDirectory, + type: "dir", + children: [], + describe: { fileName: path.basename(rootDirectory) }, + }); + //初始化文件树对象 + this.fileData = FileTree.buildFileData(this.rootDirectory); + //根据process.env.isTs更改后缀 + process.env.isTs && this.changeFileExtensionToTs(); + } + /** + * + * @param src 文件树根路径 + * @returns 文件树对象 + * @description 根据目录构造文件数对象 + */ + static buildFileData(src: string) { + const file: FileData = { + path: src, + children: [], + describe: { fileName: path.basename(src) }, + }; + if (isDirectoryOrFile(src)) {
这些地方可以注释一下,不直观
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -233,33 +237,32 @@ class Generator { data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], }, }; - - this.renderTemplates(templatePath, this.rootDirectory, options); + new FileTree(templatePath).renderTemplates(this.rootDirectory, undefined, options); } // 递归渲染ejs模板 - async renderTemplates(src: string, dest: string, options: any) { - // 确保目标目录存在 - await fs.ensureDir(dest); - - // 读取源目录中的所有文件和文件夹 - const entries = await fs.readdir(src, { withFileTypes: true }); - - for (const entry of entries) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, entry.name); - - if (entry.isDirectory()) { - // 递归处理文件夹 - await this.renderTemplates(srcPath, destPath, options); - } else { - // 读取和渲染 EJS 模板 - const content = await fs.readFile(srcPath, "utf-8"); - const rendered = ejs.render(content, options, {}); - await fs.writeFile(destPath, rendered); - } - } - } + // async renderTemplates(src: string, dest: string, options: any) {
注释不需要了
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -321,7 +324,7 @@ class Generator { * 获取当前所有文件 * @returns 当前所有文件 */ - getFiles(): Record<string, string> { + getFiles(): FileTree {
不需要了吧
create-neat
github_2023
typescript
159
xun082
uaenaTzx
@@ -0,0 +1,176 @@ +import path from "path"; +import fs from "fs-extra"; +import ejs from "ejs"; +/** + * + * @param path 路径 + * @returns 返回路径是否为文件夹 + * @description 判断是否为文件夹 + */ +function isDirectoryOrFile(path: string) { + try { + const stats = fs.statSync(path); + return stats.isDirectory(); + } catch (err) { + // 处理错误 + return false; + } +} +interface FileDescribe { + fileName: string; + fileExtension: string; + fileContent: any; +} +interface FileData { + path: string; + type?: "dir" | "file"; + children: FileData[]; + describe: Partial<FileDescribe>; +} +/** + * @description 文件树类,可以根据路径生成文件树对象,根据文件树对象创建template文件,修改文件对象后缀属性 + */ +class FileTree { + private rootDirectory: string; //文件树的根目录路径 + private fileData: FileData; //文件树对象 + constructor(rootDirectory: string) { + (this.rootDirectory = rootDirectory), + (this.fileData = { + path: rootDirectory, + type: "dir", + children: [], + describe: { fileName: path.basename(rootDirectory) }, + }); + //初始化文件树对象 + this.fileData = FileTree.buildFileData(this.rootDirectory); + //根据process.env.isTs更改后缀 + process.env.isTs && this.changeFileExtensionToTs(); + } + /** + * + * @param src 文件树根路径 + * @returns 文件树对象 + * @description 根据目录构造文件数对象 + */ + static buildFileData(src: string) { + const file: FileData = { + path: src, + children: [], + describe: { fileName: path.basename(src) }, + }; + if (isDirectoryOrFile(src)) { + file.type = "dir"; + const entries = fs.readdirSync(src, { + withFileTypes: true, + }); + for (const entry of entries) { + const subTree = this.buildFileData(path.join(src, entry.name)); + file.children?.push(subTree); + } + } else { + const fileContent = fs.readFileSync(src, "utf8"); + file.type = "file"; + file.describe = { + fileName: path.basename(src).split(".")[0], + fileExtension: path.extname(src).slice(1), + fileContent, + }; + } + return file; + } + + /** + * + * @param file 文件数对象 + * @param handleFn 处理文件树对象的函数 + * @description 遍历树的一个方法,对每个fileData对象做一次handleFn处理 + */ + traverseTree(file: FileData, handleFn: (file: FileData) => any) { + handleFn(file); + if (file.children.length) { + file.children.forEach((subFile) => this.traverseTree(subFile, handleFn)); + } + } + /** + * @description 根据process.env.isTs来更改文件数对象的后缀属性 + */ + changeFileExtensionToTs() { + //更改后缀的处理函数 + function handleExt(file: FileData) { + if (file.type === "file") { + switch (file.describe?.fileExtension) { + case "js": + file.describe.fileExtension = "ts"; + break; + case "jsx": + file.describe.fileExtension = "tsx"; + break; + default: + break; + } + } + } + this.traverseTree(this.fileData, handleExt); + } + + /** + * + * @param src 目标文件路径 + * @param file 文件树对象 + * @param options ejs对应的options参数 + * @description 将单个文件树(type==='file')通过ejs渲染成文件,只渲染文件 + */ + async fileRender(src: string, file: FileData, options: any) { + const rendered = ejs.render(file.describe?.fileContent, options, {}); + await fs.writeFile(src, rendered); + } + + /** + * + * @param dest 目标目录路径 + * @param file 文件树对象 + * @param options ejs对应的Options参数 + * @description 将文件树渲染到指定目录下形成文件 + */ + async renderTemplates(dest: string, file: FileData = this.fileData, options: any = {}) { + await fs.ensureDir(dest); + const promises = file.children.map(async (subFile) => { + const destPath = path.join( + dest, + `${subFile.describe.fileName!}${subFile.type === "file" ? "." + subFile.describe.fileExtension : ""}`, + ); + if (subFile.type === "dir" && subFile.describe) { + return this.renderTemplates(destPath, subFile, options); + } else { + return this.fileRender(destPath, subFile, options); + } + }); + await Promise.all(promises);
这里要做一个兜底,成功失败给个消息
create-neat
github_2023
typescript
146
xun082
uaenaTzx
@@ -199,7 +198,8 @@ class Generator { console.log("Files have been generated and written to disk.\n"); /* ----------拉取对应模板,并进行ejs渲染---------- */ - const templatePath = resolveApp(`./template/${this.templateName}`); + // const templatePath = join(__dirname, "../../template/", this.templateName);
不需要这个注释
create-neat
github_2023
typescript
146
xun082
uaenaTzx
@@ -42,75 +38,8 @@ export async function removeDirectory( } } -async function copyFolderRecursive(sourceDir: string, destinationDir: string) { - try { - await fs.ensureDir(destinationDir); - await fs.copy(sourceDir, destinationDir); - } catch (error) { - console.error( - chalk.red("\n 😡😡😡 An error occurred during the template download, please try again"), - error, - ); - process.exit(1); - } -} - -export async function getNpmPackage( - packageURL: string, - packageName: string, - projectName: string, - isDev?: boolean | undefined, -): Promise<void> { - const spinner = ora(chalk.bold.cyan("Creating a project...")).start(); - try { - const currentDir = resolveApp(projectName); - // 如果是dev mode,检查并使用本地模板 - if (isDev) { - const root = resolve(__dirname, "../../../../apps/"); - // 通过dist/index.js,找到模板文件的路径 - const templateDir = resolve( - root, - "template-react-web-ts/laconic-template-react-web-ts-1.0.1.tgz", - ); - const hasLocalTemplate = fs.existsSync(templateDir); - if (hasLocalTemplate) { - await getPackageFromLocal(currentDir, templateDir); - return; - } - } - const response = await axios.get(packageURL, { - responseType: "arraybuffer", - }); - const tgzPath = join(currentDir, `${packageName}-${packageVersion}.tgz`); - fs.writeFileSync(tgzPath, response.data); - - await tar.extract({ - file: tgzPath, - cwd: currentDir, - }); +export function createTemplateFile(file: string) { + console.log(join(__dirname, "../../template/", file));
不需要了
create-neat
github_2023
typescript
146
xun082
uaenaTzx
@@ -42,75 +38,8 @@ export async function removeDirectory( } } -async function copyFolderRecursive(sourceDir: string, destinationDir: string) { - try { - await fs.ensureDir(destinationDir); - await fs.copy(sourceDir, destinationDir); - } catch (error) { - console.error( - chalk.red("\n 😡😡😡 An error occurred during the template download, please try again"), - error, - ); - process.exit(1); - } -} - -export async function getNpmPackage( - packageURL: string, - packageName: string, - projectName: string, - isDev?: boolean | undefined, -): Promise<void> { - const spinner = ora(chalk.bold.cyan("Creating a project...")).start(); - try { - const currentDir = resolveApp(projectName); - // 如果是dev mode,检查并使用本地模板 - if (isDev) { - const root = resolve(__dirname, "../../../../apps/"); - // 通过dist/index.js,找到模板文件的路径 - const templateDir = resolve( - root, - "template-react-web-ts/laconic-template-react-web-ts-1.0.1.tgz", - ); - const hasLocalTemplate = fs.existsSync(templateDir); - if (hasLocalTemplate) { - await getPackageFromLocal(currentDir, templateDir); - return; - } - } - const response = await axios.get(packageURL, { - responseType: "arraybuffer", - }); - const tgzPath = join(currentDir, `${packageName}-${packageVersion}.tgz`); - fs.writeFileSync(tgzPath, response.data); - - await tar.extract({ - file: tgzPath, - cwd: currentDir, - }); +export function createTemplateFile(file: string) {
函数注释写一下
create-neat
github_2023
typescript
145
xun082
xun082
@@ -178,8 +185,8 @@ class Generator { process.env.isTs = "true"; this.pluginGenerate("typescript"); //删除typescript对应处理,防止重新处理 - const index = Object.keys(this.plugins).indexOf("typescript"); - this.plugins.splice(index, 1); + delete this.plugins.typescript; + console.log(this.plugins);
别对源对象进行操作,最好用解构的方法 const { typescrip,...rest } = this.plugins 这样
create-neat
github_2023
typescript
145
xun082
xun082
@@ -80,35 +82,34 @@ export default async function createAppTest(projectName: string, options: Record // 2. 初始化构建工具配置文件 const buildToolConfigTemplate = fs.readFileSync( - path.resolve(fs.realpathSync(process.cwd()), `./template/${buildTool}.config.js`), + resolveApp(`./template/${buildTool}.config.js`), "utf-8", ); const buildToolConfigAst = parse(buildToolConfigTemplate, { sourceType: "module", }); - fs.writeFileSync(path.resolve(rootDirectory, `${buildTool}.config.js`), buildToolConfigTemplate); + + await fs.writeFileSync( + path.resolve(rootDirectory, `${buildTool}.config.js`), + buildToolConfigTemplate, + ); // 3. 遍历 plugins,插入依赖 Object.keys(plugins).forEach((dep) => { - console.log("dep:", dep); // TODO: 更多的处理依据 plugins[dep] 后续的变化而插入 let { version } = plugins[dep]; if (!version) version = "latest"; // 默认版本号为 latest packageContent.devDependencies[dep] = version; // 插件都是以 devDependencies 安装 // TODO: 现在只有 babel-plugin-test-ljq 这一个包,先试一下,后续发包 - if (dep === "Babel") { - const pluginName = `${dep.toLowerCase()}-plugin-test-ljq`; + if (dep === "babel") { + const pluginName = `${dep}-plugin-test-ljq`; packageContent.devDependencies[pluginName] = "latest"; - delete packageContent.devDependencies["Babel"]; + delete packageContent.devDependencies["babel"];
这个也是
create-neat
github_2023
javascript
126
xun082
uaenaTzx
@@ -12,7 +12,7 @@ const buildToolConfigs = { // 添加其他构建工具的配置... }; -const pluginBable = (api, options) => { +const bablePlugin = (api, options) => {
这个文件的操作显然会引起冲突了,你可以看看插件适配构建工具那个 pr 的改动,而且现在改成 cjs 了
create-neat
github_2023
typescript
126
xun082
stitchDengg
@@ -41,7 +54,7 @@ export default class ConfigTransform { * @param context 上下文 * @returns {filename, content} filename为文件名 content为转化后得文件内容 */ - thransform(value, files, context) { + transform(value, files, context) { const file = this.getDefaultFile(); const { type, filename } = file; const transform = transforms[type];
这里函数和变量共用一个transform我觉得不太好,或许可以改下名字让语义更清晰?
create-neat
github_2023
typescript
126
xun082
stitchDengg
@@ -93,20 +79,20 @@ class GeneratorAPI { } /** - * @description 将生成器的模板文件渲染到虚拟文件树对象中。 + * @description 将 Generator 的模板文件渲染到虚拟文件树对象中。 * @param {string | object | FileMiddleware} source - 可以是以下之一: - * - 相对路径到一个目录; + * - 于项目根目录的相对路径; * - { sourceTemplate: targetFile } 映射的对象哈希; * - 自定义文件中间件函数。 * @param {object} [additionalData] - 可供模板使用的额外数据。 * @param {object} [ejsOptions] - ejs 的选项。 */ - render(source, additionalData = {}, ejsOptions = {}) { - const rootDir = (this.generator as any).rootDirectory; + render(source: string | object, additionalData: object = {}, ejsOptions: object = {}) { + const rootDir = this.generator.getRootDirectory(); // 拿到项目的根目录绝对路径
把注释移到代码上面吧 风格统一一下
create-neat
github_2023
others
94
xun082
uaenaTzx
@@ -43,7 +43,12 @@ "fs-extra": "^11.2.0", "minimist": "^1.2.8", "ora": "^5.4.1", - "tar": "^6.2.0" + "tar": "^6.2.0", + "webpack-chain": "^6.5.1", + "@babel/parser": "^7.24.0",
为什么这些会加在 core 里面
create-neat
github_2023
typescript
94
xun082
uaenaTzx
@@ -109,6 +114,24 @@ class Generator { this.plugins[pluginName], this.rootOptions, ); + // 执行plugin的入口文件,把config写进来 + const pluginEntry = await loadModule( + `packages/@plugin/plugin-${pluginName.toLowerCase()}/index.cjs`, + path.resolve(__dirname, relativePathToRoot), + ); + // 处理webpack config + if (this.buildToolConfig.buildTool === "webpack") {
这一步逻辑能抽象出来吗
create-neat
github_2023
others
94
xun082
stitchDengg
@@ -0,0 +1,37 @@ +const buildToolConfigs = { + // 支持拓展loader和plugin + webpack: () => { + const a = new RegExp();
这个正则是不是没用上,没用上可以删了
create-neat
github_2023
typescript
94
xun082
uaenaTzx
@@ -0,0 +1,70 @@ +import {
这个文件一些相关函数尽量给一些 jsdoc 注释
create-neat
github_2023
others
134
xun082
uaenaTzx
@@ -0,0 +1,190 @@ + +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + eslint: { + env: { + browser: true, + commonjs: true, + es6: true, + node: true, + }, + extends: ["eslint:recommended"], + parserOptions: { + root: true, + parser: "@babel/eslint-parser", + ecmaVersion: 2021, + sourceType: "module", + requireConfigFile: false, + }, + plugins: ['import', 'jsx-a11y'], + // rules: {
规则不要的就删了吧,给一个最基本的就行
create-neat
github_2023
others
134
xun082
uaenaTzx
@@ -1,5 +1,22 @@ { "name": "@plugin/plugin-eslint", "version": "1.0.0", - "dependencies": {} + "description": "eslint plugin for crate-neat", + "type": "module", + "main": "index.ts", + "scripts": { + "build": "tsc" + }, + "devDependencies": {
插件本身不需要这些依赖,要创建的项目才需要,已经在 generator 执行的时候传递进去了
create-neat
github_2023
typescript
134
xun082
uaenaTzx
@@ -85,11 +85,11 @@ export default async function createAppTest(projectName: string, options: Record if (!version) version = "latest"; // 默认版本号为 latest packageContent.devDependencies[dep] = version; // 插件都是以 devDependencies 安装 // TODO: 现在只有 babel-plugin-test-ljq 这一个包,先试一下,后续发包 - if (dep === "Babel") { - const pluginName = `${dep.toLowerCase()}-plugin-test-ljq`; - packageContent.devDependencies[pluginName] = "latest"; - delete packageContent.devDependencies["Babel"]; - } + // if (dep === "Babel") {
这个可以撤回
create-neat
github_2023
others
125
xun082
uaenaTzx
@@ -95,19 +95,6 @@ importers: apps/template-vue-web-ts: {} - docs:
pnpm lock 有问题吧,不会改动那么大的
create-neat
github_2023
others
130
xun082
uaenaTzx
@@ -0,0 +1,12 @@ +module.exports = (generatorAPI) => { + generatorAPI.extendPackage({ + devDependencies: { + typescript: "~5.4.0", + "@types/node": "^20.11.28", + "ts-loader": "~9.5.1" + }, + }); + generatorAPI.render('./template/tsconfig.json')
render 方法不要了,模板的加载函数目前独立出来了,还没合入,而且插件里面不用关心 template 文件的渲染
create-neat
github_2023
others
130
xun082
uaenaTzx
@@ -0,0 +1,35 @@ +const buildToolConfigs = { + // 支持拓展loader和plugin + webpack: () => { + return { + rules: [ + { + test: /\tsx?$/, // 匹配所有以 .ts 结尾的文件
匹配 ts 结尾为什么用的 tsx
create-neat
github_2023
typescript
130
xun082
uaenaTzx
@@ -97,46 +107,54 @@ class Generator { this.originalPkg = pkg; this.pkg = Object.assign({}, pkg); } + //处理单个插件的相关文件 + async pluginGenerate(pluginName: string) { + const generatorAPI = new GeneratorAPI( + pluginName, + this, + this.plugins[pluginName], + this.rootOptions, + ); + + // pluginGenerator 是一个函数,接受一个 GeneratorAPI 实例作为参数 + let pluginGenerator; + if (process.env.NODE_ENV === "DEV") { + const pluginPathInDev = `packages/@plugin/plugin-${pluginName.toLowerCase()}/generator/index.cjs`; + pluginGenerator = await loadModule( + pluginPathInDev, + path.resolve(__dirname, relativePathToRoot), + ); + } else if (process.env.NODE_ENV === "PROD") { + const pluginPathInProd = `node_modules/${pluginName.toLowerCase()}-plugin-test-ljq`; + pluginGenerator = await loadModule(pluginPathInProd, this.rootDirectory); + } else { + throw new Error("NODE_ENV is not set"); + } + if (pluginGenerator && typeof pluginGenerator === "function") { + await pluginGenerator(generatorAPI); + } + } // 创建所有插件的相关文件 async generate() { // 为每个 plugin 创建 GeneratorAPI 实例,调用插件中的 generate - + // 有限处理ts插件 + if (Object.keys(this.plugins).includes("typescript")) { + this.pluginGenerate("typescript");
ts 是否存在的环境变量需要维护
create-neat
github_2023
others
129
xun082
uaenaTzx
@@ -0,0 +1,19 @@ +module.exports = (generatorAPI) => { + console.log(Object.keys(generatorAPI));
这个不需要
create-neat
github_2023
typescript
129
xun082
uaenaTzx
@@ -51,6 +51,13 @@ const defaultConfigTransforms = { yaml: [".lintstagedrc.yaml", ".lintstagedrc.yml"], }, }), + prettier: new ConfigTransform({
仅用json吧,没必要多种类型
create-neat
github_2023
typescript
129
xun082
uaenaTzx
@@ -104,11 +106,11 @@ export default async function createAppTest(projectName: string, options: Record if (gitCheck(rootDirectory)) exec("git init", { cwd: rootDirectory }); // 安装传入的依赖 - await dependenciesInstall(rootDirectory, packageManager); - + if (process.env.NODE_ENV === "PROD") { + await dependenciesInstall(rootDirectory, packageManager); + } // 运行生成器创建项目所需文件和结构 - console.log(chalk.blue(`🚀 Invoking generators...`));
这个为啥删了
create-neat
github_2023
typescript
129
xun082
uaenaTzx
@@ -104,11 +106,11 @@ export default async function createAppTest(projectName: string, options: Record if (gitCheck(rootDirectory)) exec("git init", { cwd: rootDirectory }); // 安装传入的依赖 - await dependenciesInstall(rootDirectory, packageManager); - + if (process.env.NODE_ENV === "PROD") {
安装传入以来为何要区分环境
create-neat
github_2023
typescript
110
xun082
uaenaTzx
@@ -46,7 +46,10 @@ class Generator { let pluginGenerator; if (process.env.NODE_ENV === "DEV") { const pluginPathInDev = `packages/@plugin/plugin-${pluginName.toLowerCase()}/generator/index.cjs`; - pluginGenerator = await loadModule(pluginPathInDev, process.cwd()); + pluginGenerator = await loadModule( + pluginPathInDev, + path.resolve(__dirname, "../../../../"),
"../../../../" 能不能写活,不然后面有变动还有心智负担
create-neat
github_2023
typescript
114
xun082
uaenaTzx
@@ -4,6 +4,11 @@ interface envConfig { [props: string]: string | number; } +/** + * 创建基于环境配置的哈希值。
函数介绍的话应该是 @description 创建xxxxxxxxx
create-neat
github_2023
others
108
xun082
uaenaTzx
@@ -0,0 +1,21 @@ +{
这个文件不需要吧
create-neat
github_2023
others
108
xun082
uaenaTzx
@@ -71,6 +71,7 @@ }, "dependencies": { "@types/node": "^20.11.22", + "create-neat": "^1.0.6",
为什么要在本地安装
create-neat
github_2023
others
108
xun082
uaenaTzx
@@ -1,8 +1,8 @@ -export default (generatorAPI) => { +module.exports = (generatorAPI) => {
整体还是改成 esm 的写法吧
create-neat
github_2023
others
108
xun082
uaenaTzx
@@ -0,0 +1,36 @@ +{
这个文件删掉
create-neat
github_2023
others
108
xun082
uaenaTzx
@@ -0,0 +1,9 @@ +{
测试文件删掉
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -0,0 +1,33 @@ +export default class ConfigTransform {
相关注释可以写一下的
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -3,12 +3,64 @@ import path from "path"; import { createFiles } from "./createFiles"; import GeneratorAPI from "./GeneratorAPI"; +import ConfigTransform from "./ConfigTransform"; -function loadModule(modulePath, rootDirectory) { - const resolvedPath = path.resolve(rootDirectory, modulePath); +const ensureEOL = (str) => { + if (str.charAt(str.length - 1) !== "\n") { + return str + "\n"; + } + return str; +}; + +// 插件对应得配置文件 +const defaultConfigTransforms = { + babel: new ConfigTransform({ + file: { + js: ["babel.config.js"], + }, + }), + postcss: new ConfigTransform({ + file: { + js: ["postcss.config.js"], + json: [".postcssrc.json", ".postcssrc"], + yaml: [".postcssrc.yaml", ".postcssrc.yml"], + }, + }), + eslintConfig: new ConfigTransform({ + file: { + js: [".eslintrc.js"], + json: [".eslintrc", ".eslintrc.json"], + yaml: [".eslintrc.yaml", ".eslintrc.yml"], + }, + }), + browserslist: new ConfigTransform({ + file: { + lines: [".browserslistrc"], + }, + }), + "lint-staged": new ConfigTransform({ + file: { + js: ["lint-staged.config.js"], + json: [".lintstagedrc", ".lintstagedrc.json"], + yaml: [".lintstagedrc.yaml", ".lintstagedrc.yml"], + }, + }), +}; + +// vue项目对应得配置文件
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -3,12 +3,64 @@ import path from "path"; import { createFiles } from "./createFiles"; import GeneratorAPI from "./GeneratorAPI"; +import ConfigTransform from "./ConfigTransform"; -function loadModule(modulePath, rootDirectory) { - const resolvedPath = path.resolve(rootDirectory, modulePath); +const ensureEOL = (str) => { + if (str.charAt(str.length - 1) !== "\n") { + return str + "\n"; + } + return str; +}; + +// 插件对应得配置文件 +const defaultConfigTransforms = { + babel: new ConfigTransform({ + file: { + js: ["babel.config.js"], + }, + }), + postcss: new ConfigTransform({ + file: { + js: ["postcss.config.js"], + json: [".postcssrc.json", ".postcssrc"], + yaml: [".postcssrc.yaml", ".postcssrc.yml"], + }, + }), + eslintConfig: new ConfigTransform({ + file: { + js: [".eslintrc.js"], + json: [".eslintrc", ".eslintrc.json"], + yaml: [".eslintrc.yaml", ".eslintrc.yml"], + }, + }), + browserslist: new ConfigTransform({ + file: { + lines: [".browserslistrc"], + }, + }), + "lint-staged": new ConfigTransform({ + file: { + js: ["lint-staged.config.js"], + json: [".lintstagedrc", ".lintstagedrc.json"], + yaml: [".lintstagedrc.yaml", ".lintstagedrc.yml"], + }, + }), +}; + +// vue项目对应得配置文件 +const reservedConfigTransforms = { + vue: new ConfigTransform({ + file: { + js: ["vue.config.js"], + }, + }), +}; + +async function loadModule(modulePath, rootDirectory) { + const resolvedPath = path.resolve(rootDirectory, "../../", modulePath); try { // 尝试加载模块 - const module = require(resolvedPath); + const module = await require(resolvedPath);
esm
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -40,27 +102,71 @@ class Generator { this.plugins[pluginName], this.rootOptions, ); - console.log(generatorAPI); - console.log(pluginName); - const newPluginName = pluginName.toLowerCase(); - const pluginPath = `node_modules/${newPluginName}-plugin-test-ljq`; - const pluginGenerator = loadModule(pluginPath, this.rootDirectory); - if (pluginGenerator && typeof pluginGenerator.generator === "function") { - const i = await pluginGenerator.generator(generatorAPI); - console.log(i); + + // pluginGenerator 是一个函数,接受一个 GeneratorAPI 实例作为参数 + let pluginGenerator; + if (process.env.NODE_ENV === "DEV") { + const pluginPathInDev = `packages/@plugin/plugin-${pluginName.toLowerCase()}/generator/index.cjs`; + pluginGenerator = await loadModule(pluginPathInDev, process.cwd()); + } else if (process.env.NODE_ENV === "PROD") { + const pluginPathInProd = `node_modules/${pluginName.toLowerCase()}-plugin-test-ljq`; + pluginGenerator = await loadModule(pluginPathInProd, this.rootDirectory); + } else { + throw new Error("NODE_ENV is not set"); + } + if (pluginGenerator && typeof pluginGenerator === "function") { + await pluginGenerator(generatorAPI); } } // 在文件生成之前提取配置文件 // 整合需要安装的文件 // 这里假设 GeneratorAPI 有一个方法来更新这个 Generator 实例的 files // createFiles 函数需要你根据自己的逻辑实现文件创建和写入磁盘的逻辑 + // extract configs from package.json into dedicated files. + // 从package.json中生成额外得的文件 + await this.extractConfigFiles(); + + // 重写pakcage.json文件,消除generatorAPI中拓展package.json带来得副作用 + this.files["package.json"] = JSON.stringify(this.pkg, null, 2); + // Object.keys(this.plugins).forEach((pluginName: string) => { + // const fileName = pluginToFilename[pluginName]; + // this.files[fileName] = ""; + // }); + + console.log(this.files, "-----this.files"); // 安装文件 await createFiles(this.rootDirectory, this.files); console.log("Files have been generated and written to disk."); } + async extractConfigFiles() {
相关的函数尽量都写一下注释
create-neat
github_2023
typescript
108
xun082
stitchDengg
@@ -2,6 +2,7 @@ import fs from "node:fs"; import path from "node:path"; const appDirectory: string = fs.realpathSync(process.cwd()); +console.log(appDirectory, "------appDirectory");
debug的console.log都可以删除掉
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -0,0 +1,44 @@ +export default class ConfigTransform { + private fileDesc; // 文件类型描述 + constructor(fileDesc) { + this.fileDesc = fileDesc.file; + } + + /** + *
@descript 函数功能
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -62,12 +128,51 @@ class Generator { // 整合需要安装的文件 // 这里假设 GeneratorAPI 有一个方法来更新这个 Generator 实例的 files // createFiles 函数需要你根据自己的逻辑实现文件创建和写入磁盘的逻辑 + // extract configs from package.json into dedicated files. + // 从package.json中生成额外得的文件 + await this.extractConfigFiles(); + + // 重写pakcage.json文件,消除generatorAPI中拓展package.json带来得副作用
的 mark
create-neat
github_2023
typescript
108
xun082
stitchDengg
@@ -0,0 +1,44 @@ +export default class ConfigTransform { + private fileDesc; // 文件类型描述 + constructor(fileDesc) { + this.fileDesc = fileDesc.file; + } + + /** + * + * @param value 文件初始内容 + * @param files file tree对象(目前没用到) + * @param context 上下文 + * @returns {filename, content} filename为文件名 content为转化后得文件内容 + */ + thransform(value, files, context) { + const file = this.getDefaultFile(); + const { type, filename } = file; + const transform = transforms[type]; + const content = transform.write(filename, context, value); + return { + filename, + content, + }; + } + + /** + * 获取文件类型和文件名 + * @returns {type, filename} type为需要生成得文件类型,filename为文件名 + */ + getDefaultFile() {
尽量把函数定义写在函数调用之前
create-neat
github_2023
typescript
108
xun082
uaenaTzx
@@ -107,12 +107,14 @@ export default async function createAppTest(projectName: string, options: Record await dependenciesInstall(rootDirectory, packageManager); // 运行生成器创建项目所需文件和结构 + console.log(chalk.blue(`🚀 Invoking generators...`)); - const generators = new Generator(rootDirectory, plugins); + const generators = new Generator(rootDirectory, preset.plugins, packageContent);
preset属性在前面已经解构出来了
create-neat
github_2023
typescript
103
xun082
uaenaTzx
@@ -52,16 +63,19 @@ async function createFolder(rootDirectory: string, options: Record<string, any>) fs.mkdirSync(rootDirectory, { recursive: true }); } +// rootDirectory 由 create-neat 所在的系统根目录和用户输入的文件夹名称拼接而成 +let rootDirectory: string;
这边为什么还需要额外定义一次,函数已经传入了
create-neat
github_2023
others
101
xun082
github-actions[bot]
@@ -1,8 +1,8 @@ -export default (generatorAPI) => { +module.exports = (generatorAPI) => {
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit `module.exports = (generatorAPI) => {` 这里将 `export default` 改为了 `module.exports`,这是正确的更改。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
93
xun082
uaenaTzx
@@ -29,6 +29,8 @@ process.stdin.on("data", (key) => { // 创建项目文件夹 async function createFolder(rootDirectory: string, options: Record<string, any>) { + // 记录开发环境并设置环境变量 + process.env.NODE_ENV = options.dev ? "DEV" : "PROD";
这一步在这个文件里重复写了吧。 环境变量按照规范一般是在函数外面注册的,最好不要写在里面
create-neat
github_2023
typescript
90
xun082
github-actions[bot]
@@ -42,10 +42,12 @@ class Generator { ); console.log(generatorAPI); console.log(pluginName); - const pluginPath = `${pluginName}/generator`; + const newPluginName = pluginName.toLowerCase(); + const pluginPath = `node_modules/${newPluginName}-plugin-test-ljq`;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在这个更改中,插件路径被修改为小写,并且添加了一个新的插件依赖包`babel-plugin-test-ljq`。建议检查是否需要更新其他相关代码以适应这些更改。 ```diff - const pluginPath = `${pluginName}/generator`; + const newPluginName = pluginName.toLowerCase(); + const pluginPath = `node_modules/${newPluginName}-plugin-test-ljq`; ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
90
xun082
github-actions[bot]
@@ -42,10 +42,12 @@ ); console.log(generatorAPI); console.log(pluginName); - const pluginPath = `${pluginName}/generator`; + const newPluginName = pluginName.toLowerCase(); + const pluginPath = `node_modules/${newPluginName}-plugin-test-ljq`; const pluginGenerator = loadModule(pluginPath, this.rootDirectory); - if (pluginGenerator && typeof pluginGenerator.generate === "function") { - await pluginGenerator.generate(generatorAPI); + if (pluginGenerator && typeof pluginGenerator.generator === "function") { + const i = await pluginGenerator.generator(generatorAPI); + console.log(i);
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在这个更改中,调用了`pluginGenerator.generator`函数并打印了返回值。请确保这个函数的返回值被正确处理和使用。 ```diff + const pluginGenerator = loadModule(pluginPath, this.rootDirectory); if (pluginGenerator && typeof pluginGenerator.generator === "function") { - await pluginGenerator.generate(generatorAPI); + const i = await pluginGenerator.generator(generatorAPI); + console.log(i); } ``` 请注意,以上是对每个文件更改的简要总结,不涉及逻辑或功能方面的问题。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -1,7 +1,8 @@ -// import fs from 'fs' - +import fs from "fs"; +import path from "path"; +import ejs from "ejs"; /**
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在导入模块的时候,建议按照一定的顺序进行导入,例如将相同来源的模块放在一起。此外,可以在每个导入语句之间添加空行,以提高可读性。 ```diff +import ejs from "ejs"; +import fs from "fs"; +import path from "path"; ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -23,11 +24,67 @@ /** * @description 扩展项目的 package.json 内容 - * @param fields 合并内容 + * @param fields 合并内容 * @param {object} [options] 操作选项 */ extendPackage(fields, options = {}) { - console.log(fields, options); + // 扩展 package.json + // options 就是一个可扩展对象 + const extendOptions = { + // 是否进行修剪操作 + prune: false, + // 合并字段 + merge: true, + // 是否警告不兼容的版本 + warnIncompatibleVersions: true, + // 是否强制覆盖 + forceOverwrite: false, + // 传入的配置项 + ...options, + };
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit `extendPackage` 方法中的参数 `fields` 和 `options` 没有进行类型注解,请为它们添加类型注解,以提高代码的可读性和可维护性。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -23,11 +24,67 @@ /** * @description 扩展项目的 package.json 内容 - * @param fields 合并内容 + * @param fields 合并内容 * @param {object} [options] 操作选项 */ extendPackage(fields, options = {}) { - console.log(fields, options); + // 扩展 package.json + // options 就是一个可扩展对象 + const extendOptions = { + // 是否进行修剪操作 + prune: false, + // 合并字段 + merge: true, + // 是否警告不兼容的版本 + warnIncompatibleVersions: true, + // 是否强制覆盖 + forceOverwrite: false, + // 传入的配置项 + ...options, + }; + // 获取当前项目的package.json + const pkgPath = path.resolve((this.generator as any).rootDirectory, "package.json"); + // 读取package.json中的内容 + let pkg = {}; + try { + pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + } catch (err) { + console.error(`Failed to read package.json: ${err}`); + return; + }
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在读取 `package.json` 文件时,如果发生错误,当前的处理方式是打印错误消息并返回。建议在这种情况下,抛出一个异常或者返回一个错误对象,以便调用方能够更好地处理错误。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -23,11 +24,67 @@ /** * @description 扩展项目的 package.json 内容 - * @param fields 合并内容 + * @param fields 合并内容 * @param {object} [options] 操作选项 */ extendPackage(fields, options = {}) { - console.log(fields, options); + // 扩展 package.json + // options 就是一个可扩展对象 + const extendOptions = { + // 是否进行修剪操作 + prune: false, + // 合并字段 + merge: true, + // 是否警告不兼容的版本 + warnIncompatibleVersions: true, + // 是否强制覆盖 + forceOverwrite: false, + // 传入的配置项 + ...options, + }; + // 获取当前项目的package.json + const pkgPath = path.resolve((this.generator as any).rootDirectory, "package.json"); + // 读取package.json中的内容 + let pkg = {}; + try { + pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + } catch (err) { + console.error(`Failed to read package.json: ${err}`); + return; + } + // 将filds合并到package.json中 + for (const key in fields) { + const value = fields[key]; + const existing = pkg[key]; + // 如果merge为false或者key不在package.json中 则直接赋值 + if (!extendOptions.merge || !(key in pkg)) { + pkg[key] = value; + } else if (Array.isArray(value) && Array.isArray(existing)) { + // 如果是数组则合并 且去重 + pkg[key] = existing.concat(value.filter((v) => existing.indexOf(v) < 0)); + } else if (typeof value === "object" && typeof existing === "object") { + // 如果是对象则合并 + pkg[key] = { ...existing, ...value }; + } else { + pkg[key] = value; + } + } + // 如果prune为true 则删除空字段 + if (extendOptions.prune) { + for (const key in pkg) { + if (pkg[key] === null) { + delete pkg[key]; + } + } + } + // 写入package.json + try { + console.log("explosion", pkg); + fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2)); + } catch (err) { + console.error(`Failed to write package.json: ${err}`); + return; + }
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit `extendPackage` 方法中的合并逻辑可以进一步优化。目前的实现使用了多个条件判断和循环来处理不同的情况,导致代码复杂度较高。建议使用现有的工具函数或库来简化合并操作,例如使用 `lodash.merge` 或 `Object.assign` 等方法。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -40,7 +97,38 @@ * @param {object} [ejsOptions] - ejs 的选项。 */ render(source, additionalData = {}, ejsOptions = {}) { - console.log(source, additionalData, ejsOptions); + const rootDir = (this.generator as any).rootDirectory; + let content = ""; + // 处理模板路径 + if (typeof source === "string") { + // 如果是字符串 则拼接路径 + const templatePath = path.resolve(rootDir, source); + if (!fs.existsSync(templatePath)) { + console.error(`Template ${source} not found`); + return; + } + content = fs.readFileSync(templatePath, "utf-8"); + } else if (typeof source === "object") { + for (const sourceTemplate in source) { + const targetFile = source[sourceTemplate]; + const templatePath = path.resolve(rootDir, sourceTemplate); + if (!fs.existsSync(templatePath)) { + console.error(`Template ${sourceTemplate} not found`); + continue; + } + const templateContent = fs.readFileSync(templatePath, "utf-8"); + const renderedContent = ejs.render(templateContent, additionalData, ejsOptions); + fs.writeFileSync(path.resolve(rootDir, targetFile), renderedContent); + } + return; + } else { + console.error("Invalid template source"); + return; + } + // 渲染模板 + const renderedContent = ejs.render(content, additionalData, ejsOptions); + console.log(renderedContent); + return renderedContent;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit `render` 方法中的路径处理部分存在一些问题。首先,在处理模板路径时,如果模板文件不存在,当前的处理方式是打印错误消息并返回。建议在这种情况下,抛出一个异常或者返回一个错误对象。其次,在处理多个模板文件时,如果其中某个模板文件不存在,当前的处理方式是打印错误消息并继续处理下一个模板文件。建议在这种情况下,抛出一个异常或者返回一个错误对象,并停止后续的处理。 此外,建议在代码中添加适当的注释,以解释每个方法的作用和参数的含义,提高代码的可读性和可维护性。 以上是对 `packages/core/src/utils/GeneratorAPI.ts` 文件的变更的一些问题和建议,请参考并进行相应的修改。 <!-- This is an auto-generated reply by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -36,31 +36,35 @@ ([dep, version]) => `${dep}@${version}`, ); // 执行具体命令 - try{const pm = spawn( - packageManager + (process.platform === "win32" ? ".cmd" : ""), - [installCommand[packageManager], installParams[packageManager], ...devDepsArray], - { - stdio: "ignore", - cwd: packageJsonFile, - }, - ); + try { + const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""), + [installCommand[packageManager], installParams[packageManager], ...devDepsArray], + { + stdio: "ignore", + cwd: packageJsonFile, + }, + ); - // 监听安装命令的输出 - pm.on("close", (code) => { - if (code === 0) { - // code为0代表安装成功 - resolve("devDependencies installed successfully."); - console.log("devDependencies installed successfully."); - } else { - console.error( - `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, - ); - reject(`${packageManager} ${installCommand[packageManager]} exited with code ${code}`); - } - }); - }catch(err){ - console.log("Installing devDependencies failed: ",err) - }} else { + // 监听安装命令的输出 + pm.on("close", (code) => { + if (code === 0) { + // code为0代表安装成功 + resolve("devDependencies installed successfully."); + console.log("devDependencies installed successfully."); + } else { + console.error( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + reject( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + } + }); + } catch (err) { + console.log("Installing devDependencies failed: ", err); + } + } else { console.log("No devDependencies found in package.json."); reject("No devDependencies found in package.json."); }
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit > Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [79-79] 文件末尾缺少换行符。 建议在文件末尾添加一个换行符。 ```diff export default dependenciesInstall; +80: ``` 以上是对`packages/core/src/utils/dependenciesInstall.ts`的修改进行的审查。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
80
xun082
uaenaTzx
@@ -1,8 +1,2 @@ {
ignore掉
create-neat
github_2023
typescript
80
xun082
uaenaTzx
@@ -1,7 +1,22 @@ // Generator.ts +import path from "path"; + import { createFiles } from "./createFiles"; import GeneratorAPI from "./GeneratorAPI"; +function loadModule(modulePath, rootDirectory) {
loadModule 考虑独立到 utils 里作为一个方法,其他地方也有可能会调用的
create-neat
github_2023
typescript
80
xun082
uaenaTzx
@@ -1,7 +1,22 @@ // Generator.ts +import path from "path"; + import { createFiles } from "./createFiles"; import GeneratorAPI from "./GeneratorAPI"; +function loadModule(modulePath, rootDirectory) { + const resolvedPath = path.resolve(rootDirectory, modulePath); + try { + // 尝试加载模块 + const module = require(resolvedPath);
要不改成import的动态引入?
create-neat
github_2023
typescript
80
xun082
uaenaTzx
@@ -26,7 +40,8 @@ class Generator { this.plugins[pluginName], this.rootOptions, ); - + console.log(generatorAPI);
日志没必要的话可以去了
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -36,31 +36,35 @@ const dependenciesInstall = (packageJsonFile: string, packageManager: string): P ([dep, version]) => `${dep}@${version}`, ); // 执行具体命令 - try{const pm = spawn( - packageManager + (process.platform === "win32" ? ".cmd" : ""), - [installCommand[packageManager], installParams[packageManager], ...devDepsArray], - { - stdio: "ignore", - cwd: packageJsonFile, - }, - ); + try { + const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""), + [installCommand[packageManager], installParams[packageManager], ...devDepsArray], + { + stdio: "ignore", + cwd: packageJsonFile, + }, + ); - // 监听安装命令的输出 - pm.on("close", (code) => { - if (code === 0) { - // code为0代表安装成功 - resolve("devDependencies installed successfully."); - console.log("devDependencies installed successfully."); - } else { - console.error( - `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, - ); - reject(`${packageManager} ${installCommand[packageManager]} exited with code ${code}`); - } - }); - }catch(err){ - console.log("Installing devDependencies failed: ",err) - }} else { + // 监听安装命令的输出 + pm.on("close", (code) => { + if (code === 0) { + // code为0代表安装成功 + resolve("devDependencies installed successfully."); + console.log("devDependencies installed successfully."); + } else { + console.error( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + reject( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + } + }); + } catch (err) { + console.log("Installing devDependencies failed: ", err); + } + } else {
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在安装devDependencies的代码块中,缺少错误处理。如果发生错误,应该记录错误消息并拒绝Promise。 ```diff // 执行具体命令 try { const pm = spawn( packageManager + (process.platform === "win32" ? ".cmd" : ""), [installCommand[packageManager], installParams[packageManager], ...devDepsArray], { stdio: "ignore", cwd: packageJsonFile, }, ); // 监听安装命令的输出 pm.on("close", (code) => { if (code === 0) { // code为0代表安装成功 resolve("devDependencies installed successfully."); console.log("devDependencies installed successfully."); } else { console.error( `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, ); reject( `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, ); } }); } catch (err) { console.log("Installing devDependencies failed: ", err); } } else { console.log("No devDependencies found in package.json."); reject("No devDependencies found in package.json."); } ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -0,0 +1,25 @@ +import path from "path"; +interface LoadModuleType { + generate(generatorAPI): Promise<any>; +} + +/** + * @description 加载模块 + * @param {string} modulePath 模块路径 + * @param {string} rootDirectory 根目录 + * @returns {Promise<LoadModuleType | null>} 返回加载的模块 + * */ +export default async function loadModule( + modulePath: string, + rootDirectory: string,
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在`loadModule`函数的参数列表中,建议为`modulePath`和`rootDirectory`添加类型注解,以提高代码的可读性和可维护性。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -0,0 +1,25 @@ +import path from "path"; +interface LoadModuleType { + generate(generatorAPI): Promise<any>; +} + +/** + * @description 加载模块 + * @param {string} modulePath 模块路径 + * @param {string} rootDirectory 根目录 + * @returns {Promise<LoadModuleType | null>} 返回加载的模块 + * */ +export default async function loadModule( + modulePath: string, + rootDirectory: string, +): Promise<LoadModuleType | null> { + const resolvedPath = path.resolve(rootDirectory, modulePath);
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 建议在使用`path.resolve`方法之前,对`rootDirectory`进行必要的校验,确保其是一个有效的目录路径。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -0,0 +1,25 @@ +import path from "path"; +interface LoadModuleType { + generate(generatorAPI): Promise<any>; +} + +/** + * @description 加载模块 + * @param {string} modulePath 模块路径 + * @param {string} rootDirectory 根目录 + * @returns {Promise<LoadModuleType | null>} 返回加载的模块 + * */ +export default async function loadModule( + modulePath: string, + rootDirectory: string, +): Promise<LoadModuleType | null> { + const resolvedPath = path.resolve(rootDirectory, modulePath); + try { + const module = await import(resolvedPath); + return module;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在使用`import`语句动态加载模块时,建议添加错误处理机制,以捕获可能发生的异常情况,并进行适当的处理。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -0,0 +1,25 @@ +import path from "path"; +interface LoadModuleType { + generate(generatorAPI): Promise<any>; +} + +/** + * @description 加载模块 + * @param {string} modulePath 模块路径 + * @param {string} rootDirectory 根目录 + * @returns {Promise<LoadModuleType | null>} 返回加载的模块 + * */ +export default async function loadModule( + modulePath: string, + rootDirectory: string, +): Promise<LoadModuleType | null> { + const resolvedPath = path.resolve(rootDirectory, modulePath); + try { + const module = await import(resolvedPath); + return module; + } catch (error) { + // 处理加载模块失败的情况 + console.error(`Error loading module at ${resolvedPath}:`, error); + return null;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 建议在处理加载模块失败的情况时,除了打印错误消息外,还可以考虑记录错误日志或采取其他适当的措施,以便更好地追踪和排查问题。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -1,7 +1,8 @@ -// import fs from 'fs' - +import fs from "fs"; +import path from "path"; +import ejs from "ejs"; /** - * @description 为执行插件 generator 提供系一列 api + * @description 为执行 generator 提供系一列 api
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在导入模块的部分,建议按照一定的顺序进行导入,并且将每个导入语句单独放在一行。这样可以提高代码的可读性和维护性。 ```diff +import ejs from "ejs"; +import fs from "fs"; +import path from "path"; ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -1,7 +1,22 @@ // Generator.ts +import path from "path"; + import { createFiles } from "./createFiles"; import GeneratorAPI from "./GeneratorAPI"; +function loadModule(modulePath, rootDirectory) { + const resolvedPath = path.resolve(rootDirectory, modulePath); + try { + // 尝试加载模块 + const module = require(resolvedPath); + return module; + } catch (error) { + // 处理加载模块失败的情况 + console.error(`Error loading module at ${resolvedPath}:`, error); + return null; + } +} +
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 这个文件引入了一个新的函数`loadModule`,用于根据给定的路径加载模块。在加载模块失败时,它会记录错误消息并返回`null`。请注意,这个函数使用了`require`语句,这可能会导致一些安全问题。建议使用更安全的方式来加载模块。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
80
xun082
github-actions[bot]
@@ -10,7 +25,6 @@ private plugins: Record<string, any>; private files: Record<string, string> = {}; private rootOptions: Record<string, any> = {}; - constructor(rootDirectory: string, plugins = {}) { this.rootDirectory = rootDirectory; this.plugins = plugins;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在构造函数中,添加了对`plugins`参数的处理。然而,在这个函数中没有对`plugins`参数进行任何验证或检查。建议在接收到`plugins`参数后,对其进行验证和处理,以确保传递的参数是有效的。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
58
xun082
github-actions[bot]
@@ -7,8 +7,8 @@ body: label: "Is there an existing issue that is already proposing this?" description: "Please search [here](./?q=is%3Aissue) to see if an issue already exists for the feature you are requesting" options: - - label: "I have searched the existing issues" - required: true + - label: "I have searched the existing issues" + required: true
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在 `Is there an existing issue that is already proposing this?` 选项中,缺少了 `required: true` 属性。 ```diff - - label: "I have searched the existing issues" - required: true + - label: "I have searched the existing issues" required: true ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
58
xun082
github-actions[bot]
@@ -36,31 +36,35 @@ const dependenciesInstall = (packageJsonFile: string, packageManager: string): P ([dep, version]) => `${dep}@${version}`, ); // 执行具体命令 - try{const pm = spawn( - packageManager + (process.platform === "win32" ? ".cmd" : ""), - [installCommand[packageManager], installParams[packageManager], ...devDepsArray], - { - stdio: "ignore", - cwd: packageJsonFile, - }, - ); + try { + const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""), + [installCommand[packageManager], installParams[packageManager], ...devDepsArray], + { + stdio: "ignore", + cwd: packageJsonFile, + }, + ); - // 监听安装命令的输出 - pm.on("close", (code) => { - if (code === 0) { - // code为0代表安装成功 - resolve("devDependencies installed successfully."); - console.log("devDependencies installed successfully."); - } else { - console.error( - `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, - ); - reject(`${packageManager} ${installCommand[packageManager]} exited with code ${code}`); - } - }); - }catch(err){ - console.log("Installing devDependencies failed: ",err) - }} else { + // 监听安装命令的输出 + pm.on("close", (code) => { + if (code === 0) { + // code为0代表安装成功 + resolve("devDependencies installed successfully."); + console.log("devDependencies installed successfully."); + } else { + console.error( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + reject( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + } + }); + } catch (err) { + console.log("Installing devDependencies failed: ", err); + } + } else {
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在安装devDependencies时,添加了异常处理的代码块。这是一个很好的实践,以确保在安装过程中出现错误时能够进行适当的处理。然而,在捕获异常后,只是简单地打印了错误消息,并没有采取任何其他措施来处理错误或提供更详细的错误信息。建议在这里添加适当的错误处理逻辑,例如记录错误日志、向用户显示错误消息或执行其他必要的操作。 ```diff try { const pm = spawn( packageManager + (process.platform === "win32" ? ".cmd" : ""), [installCommand[packageManager], installParams[packageManager], ...devDepsArray], { stdio: "ignore", cwd: packageJsonFile, }, ); // 监听安装命令的输出 pm.on("close", (code) => { if (code === 0) { // code为0代表安装成功 resolve("devDependencies installed successfully."); console.log("devDependencies installed successfully."); } else { console.error( `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, ); reject( `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, ); } }); } catch (err) { console.log("Installing devDependencies failed: ", err); } } else { ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
58
xun082
github-actions[bot]
@@ -36,31 +36,35 @@ ([dep, version]) => `${dep}@${version}`, ); // 执行具体命令 - try{const pm = spawn( - packageManager + (process.platform === "win32" ? ".cmd" : ""), - [installCommand[packageManager], installParams[packageManager], ...devDepsArray], - { - stdio: "ignore", - cwd: packageJsonFile, - }, - ); + try { + const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""), + [installCommand[packageManager], installParams[packageManager], ...devDepsArray], + { + stdio: "ignore", + cwd: packageJsonFile, + }, + ); - // 监听安装命令的输出 - pm.on("close", (code) => { - if (code === 0) { - // code为0代表安装成功 - resolve("devDependencies installed successfully."); - console.log("devDependencies installed successfully."); - } else { - console.error( - `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, - ); - reject(`${packageManager} ${installCommand[packageManager]} exited with code ${code}`); - } - }); - }catch(err){ - console.log("Installing devDependencies failed: ",err) - }} else { + // 监听安装命令的输出 + pm.on("close", (code) => { + if (code === 0) { + // code为0代表安装成功 + resolve("devDependencies installed successfully."); + console.log("devDependencies installed successfully."); + } else { + console.error( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + reject( + `${packageManager} ${installCommand[packageManager]} exited with code ${code}`, + ); + } + }); + } catch (err) { + console.log("Installing devDependencies failed: ", err); + } + } else { console.log("No devDependencies found in package.json."); reject("No devDependencies found in package.json."); }
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit > Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [79-79] 文件末尾缺少换行符。建议在文件末尾添加一个换行符。 ```diff export default dependenciesInstall; ``` 以上是对 `packages/core/src/utils/dependenciesInstall.ts` 文件更改的评论。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
25
xun082
github-actions[bot]
@@ -0,0 +1,28 @@ +#!/bin/sh + +# 获取两个参数:起始SHA和结束SHA +start_sha=$1 +end_sha=$2 + +# 设置颜色变量 +RED='\033[0;31m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 定义提交信息规范函数 +check_commit_message() { + commit_msg="$1" + # 提交信息必须以特定关键词开头,后面可以跟着提交信息和issue号(可选) + if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|ci): .+( #[0-9]+)?$"; then
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 建议在正则表达式中使用`^`和`$`来确保匹配整个字符串,以避免不必要的匹配。修改为: ```diff - if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|ci): .+( #[0-9]+)?$"; then + if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|ci): .+( #[0-9]+)?$"; then ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
25
xun082
github-actions[bot]
@@ -0,0 +1,28 @@ +#!/bin/sh + +# 获取两个参数:起始SHA和结束SHA +start_sha=$1 +end_sha=$2 + +# 设置颜色变量 +RED='\033[0;31m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 定义提交信息规范函数 +check_commit_message() { + commit_msg="$1" + # 提交信息必须以特定关键词开头,后面可以跟着提交信息和issue号(可选) + if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|ci): .+( #[0-9]+)?$"; then + echo -e "${RED}Error:${NC} Commit message format is incorrect. It should be '${BLUE}(feat|fix|docs|style|refactor|test|chore|ci): commit message (?issue_number)${NC}'." >&2 + exit 1 + fi +} + +# 遍历从start_sha到end_sha的所有提交 +for sha in $(git rev-list $start_sha..$end_sha); do + commit_msg=$(git show --format=%B -s $sha) + check_commit_message "$commit_msg" +done
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 建议在`for`循环中添加大括号以避免潜在的问题。修改为: ```diff - for sha in $(git rev-list $start_sha..$end_sha); do + for sha in $(git rev-list $start_sha..$end_sha) + do commit_msg=$(git show --format=%B -s $sha) check_commit_message "$commit_msg" done ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
25
xun082
github-actions[bot]
@@ -0,0 +1,28 @@ +#!/bin/sh + +# 获取两个参数:起始SHA和结束SHA +start_sha=$1 +end_sha=$2 + +# 设置颜色变量 +RED='\033[0;31m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 定义提交信息规范函数 +check_commit_message() { + commit_msg="$1" + # 提交信息必须以特定关键词开头,后面可以跟着提交信息和issue号(可选) + if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|ci): .+( #[0-9]+)?$"; then + echo -e "${RED}Error:${NC} Commit message format is incorrect. It should be '${BLUE}(feat|fix|docs|style|refactor|test|chore|ci): commit message (?issue_number)${NC}'." >&2 + exit 1 + fi +} + +# 遍历从start_sha到end_sha的所有提交 +for sha in $(git rev-list $start_sha..$end_sha); do + commit_msg=$(git show --format=%B -s $sha) + check_commit_message "$commit_msg" +done + +echo -e "${BLUE}Commit message check passed.${NC}\n"
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 建议在输出信息的末尾添加换行符以提高可读性。修改为: ```diff - echo -e "${BLUE}Commit message check passed.${NC}\n" + echo -e "${BLUE}Commit message check passed.${NC}" ``` 以上是对`scripts/check_commit_msg.sh`文件的修改建议。请注意,这些建议仅供参考,您可以根据实际情况进行调整。 <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
63
xun082
xun082
@@ -7,6 +7,9 @@ import minimist from "minimist"; import { getPackageJsonInfo, createApp } from "./utils"; import createAppTest from "./utils/createAppTest"; +// todo 防止报错 +console.log(createApp);
这个打印删了,对于导入了并没有使用的变量直接删掉,下面的也是,console.log(execSync);这个
create-neat
github_2023
typescript
49
xun082
uaenaTzx
@@ -0,0 +1,65 @@ +import fs from "fs"; +import { spawn } from "child_process"; +import path from "path"; +/**
注释和 import 间隔一行 讲参数前说明函数的作用
create-neat
github_2023
typescript
49
xun082
uaenaTzx
@@ -0,0 +1,65 @@ +import fs from "fs"; +import { spawn } from "child_process"; +import path from "path"; +/** + * + * @param packageJsonFile packageJson文件父路径 + * @param packageManager 包管理器 + */ +const dependenciesInstall = (packageJsonFile: string, packageManager: string) => { + /** 不同安装方式的命令枚举 */ + const installCommand = { + npm: "install", + pnpm: "add", + yarn: "add", + }; + + const installParams = { + npm: "--save-dev", + pnpm: "--save-dev", + yarn: "--dev", + }; + + const packageJsonPath = path.join(packageJsonFile, "package.json"); + + return new Promise((resolve, reject) => { + try { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")); + const devDependencies = packageJson.devDependencies; + + if (devDependencies) { + console.log("Installing devDependencies..."); + const devDepsArray = Object.entries(devDependencies).map( + ([dep, version]) => `${dep}@${version}`, + ); + const pm = spawn(
可以考虑在函数的一些关键地方加注释,清晰一点
create-neat
github_2023
others
65
xun082
uaenaTzx
@@ -4,5 +4,27 @@ "source.fixAll.eslint": "explicit" }, "typescript.tsdk": "node_modules/typescript/lib", - "cSpell.words": ["interaciton"] + "cSpell.words": [
这个文件ignore掉吧
create-neat
github_2023
typescript
65
xun082
uaenaTzx
@@ -60,15 +60,20 @@ export default async function createAppTest(projectName: string, options: Record // 获取用户选择预设 const preset: Preset = await projectSelect(); - const { packageManager } = preset; - + const { packageManager, npmSource } = preset; // 创建package.json console.log(chalk.blue(`\n📄 Generating package.json...`)); const packageContent = { name: projectName, version: "0.1.0", private: true, - devDependencies: {}, + devDependencies: {
测试依赖的不需要吧
create-neat
github_2023
typescript
65
xun082
uaenaTzx
@@ -0,0 +1,41 @@ +import https from "https"; + +import getPackageJsonInfo from "./getPackageInfo"; +// 获取npm源以及最快的npm源 +export const getNpmSource = () => { + const npmJson: any = getPackageJsonInfo("../../../../registries.json", true); + const npmSources: any = []; + for (const key in npmJson) { + npmSources.push({ label: key, value: npmJson[key].registry }); + } + const checkSourceSpeed = (source: any) => { + return new Promise((resolve, reject) => {
要不用 async/await 写,结构更清晰一点
create-neat
github_2023
others
65
xun082
uaenaTzx
@@ -4,5 +4,24 @@ "source.fixAll.eslint": "explicit" }, "typescript.tsdk": "node_modules/typescript/lib", - "cSpell.words": ["interaciton"] + "workbench.colorCustomizations": {
还是有欸
create-neat
github_2023
others
59
xun082
uaenaTzx
@@ -15,7 +15,8 @@ "directory": "packages/core" }, "bin": { - "create-neat": "./dist/index.js" + "create-neat": "./dist/index.js", + "c": "./dist/index.js"
what
create-neat
github_2023
typescript
50
xun082
github-actions[bot]
@@ -36,8 +36,8 @@ const dependenciesInstall = (packageJsonFile: string, packageManager: string): P ([dep, version]) => `${dep}@${version}`, ); // 执行具体命令 - const pm = spawn( - packageManager, + try{const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""),
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在执行具体命令之前,应该添加错误处理逻辑,以捕获可能的异常。建议使用`try-catch`语句包裹代码块,并在`catch`块中打印错误信息。 ```diff try { + const pm = spawn( + packageManager + (process.platform === "win32" ? ".cmd" : ""), [installCommand[packageManager], installParams[packageManager], ...devDepsArray], { stdio: "ignore", ``` <!-- This is an auto-generated reply by OSS CodeRabbit -->
create-neat
github_2023
typescript
50
xun082
github-actions[bot]
@@ -58,7 +58,9 @@ const dependenciesInstall = (packageJsonFile: string, packageManager: string): P reject(`${packageManager} ${installCommand[packageManager]} exited with code ${code}`); } }); - } else { + }catch(err){ + console.log("Installing devDependencies failed: ",err) + }} else {
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 在`try`块内部,应该添加对异常的处理逻辑。建议使用`try-catch`语句包裹代码块,并在`catch`块中打印错误信息。 ```diff } catch (err) { + console.log("Installing devDependencies failed: ", err); } } else { console.log("No devDependencies found in package.json."); reject("No devDependencies found in package.json."); } ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
typescript
50
xun082
github-actions[bot]
@@ -69,4 +71,4 @@ const dependenciesInstall = (packageJsonFile: string, packageManager: string): P }); }; -export default dependenciesInstall; +export default dependenciesInstall;
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 文件末尾缺少换行符,请在文件末尾添加一个空行。 ```diff export default dependenciesInstall; + ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
50
xun082
github-actions[bot]
@@ -0,0 +1,33 @@ +# Getting Started with Create-NEAT + +### README.md + +- zh_CN [简体中文](README.md) +- en [English](README-EN.md) +
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 这些行添加了支持中英文切换的readme文件的说明。建议在这些行之前添加一个空行,以提高可读性。 ```diff + # Getting Started with Create-NEAT ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
50
xun082
github-actions[bot]
@@ -0,0 +1,33 @@ +# Getting Started with Create-NEAT + +### README.md + +- zh_CN [简体中文](README.md) +- en [English](README-EN.md) + +This project was bootstrapped with [create-neat](https://github.com/xun082/create-neat). + +## How To Run &Build + +### Run The Project + +Execute in development mode
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 这些行提供了在开发模式下运行项目的说明。建议在代码块前后添加空行,以提高可读性。 ```diff + ### Run The Project Execute in development mode ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
50
xun082
github-actions[bot]
@@ -0,0 +1,33 @@ +# Getting Started with Create-NEAT + +### README.md + +- zh_CN [简体中文](README.md) +- en [English](README-EN.md) + +This project was bootstrapped with [create-neat](https://github.com/xun082/create-neat). + +## How To Run &Build + +### Run The Project + +Execute in development mode +``` +${packageManager} run start +``` +Open[ http://localhost:3000 ]( http://localhost:3000 )To view in a browser.
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 这些行提供了在浏览器中查看项目的说明。建议在代码块前后添加空行,以提高可读性。 ```diff + Open[ http://localhost:3000 ]( http://localhost:3000 )To view in a browser. ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->
create-neat
github_2023
others
50
xun082
github-actions[bot]
@@ -0,0 +1,33 @@ +# Getting Started with Create-NEAT + +### README.md + +- zh_CN [简体中文](README.md) +- en [English](README-EN.md) + +This project was bootstrapped with [create-neat](https://github.com/xun082/create-neat). + +## How To Run &Build + +### Run The Project + +Execute in development mode +``` +${packageManager} run start +``` +Open[ http://localhost:3000 ]( http://localhost:3000 )To view in a browser. +If you make edits, the page will be reloaded +You will also see any lint errors in the console. + +### Build The Project + +Execute +``` + ${packageManager} run build +```
<img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit 这些行提供了打包项目的说明。建议在代码块前后添加空行,以提高可读性。 ```diff + ### Build The Project Execute ``` <!-- This is an auto-generated comment by OSS CodeRabbit -->