Skip to content

Commit

Permalink
Merge pull request #7 from lexmin0412/f-20240511-generate-refactor
Browse files Browse the repository at this point in the history
refactor(api): 生成逻辑抽离为单独的 Generator 类
  • Loading branch information
lexmin0412 authored May 17, 2024
2 parents f55ec91 + c2541d2 commit 7f9d289
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 23 deletions.
26 changes: 4 additions & 22 deletions packages/api/src/api/generate.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { loadBlock } from "../utils";
import { getConfig } from "@readue/config"
import type { ReadueBlockFunction } from '@readue/config'
import { Generator } from "../utils";

/**
* 判断是否是私有包
Expand Down Expand Up @@ -52,23 +50,7 @@ export const generate4SinglePkg = (pkgJson: Record<string, unknown>) => {
* 生成 Monorepo 的 README 内容
* @param pkgJson 仓库的 package.json 内容
*/
export const generate4Monorepo = (pkgJson: Record<string, any>, cwd: string) => {
let readmeLines: string[] = []
const config = getConfig(cwd)

// 根据 列表生成 README.md 中的信息
const blockFuncs = loadBlock(process.cwd())
blockFuncs?.map((funcItem: ReadueBlockFunction)=>{
const { name, content } = funcItem(config, pkgJson)
console.log(`[info] 执行块插件 ${name} - 开始`);
readmeLines = [
...readmeLines,
...content,
''
]
console.log(`[info] 执行块插件 ${name} - 结束`);
console.log('')
})

return readmeLines;
export const generate4Monorepo = (_pkgJson: Record<string, any>, cwd: string) => {
const generator = new Generator(cwd)
return generator.loadBlocks().gen()
};
45 changes: 44 additions & 1 deletion packages/api/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path'
import * as fs from 'fs'
import { getConfig } from '@readue/config'
import { ReadueBlockFunction, getConfig } from '@readue/config'

// 简单判断,当存在 pnpm-workspace.yaml 文件时,则认为是 monorepo
export const isMonorepo = (cwd: string) => {
Expand All @@ -13,3 +13,46 @@ export const loadBlock = (cwd: string) => {
return require(item).default
})
}

/**
* 内容生成器
*/
export class Generator {

constructor(public cwd: string = process.cwd()) {}

/**
* 块插件列表
*/
blocks: ReadueBlockFunction[] = []

/**
* 加载块插件
*/
loadBlocks() {
const config = getConfig(this.cwd)
config.blocks?.list.forEach(element => {
this.blocks.push(require(element).default as ReadueBlockFunction)
});
return this
}

/**
* 生成内容
*/
gen() {
const config = getConfig(this.cwd)
const content = fs.readFileSync(path.resolve(this.cwd, 'package.json')).toString()
const pkgJson = JSON.parse(content)

const contentLines: string[] = []
this.blocks.forEach(block=>{
const { name, content } = block(config, pkgJson)
console.log(`[info] 执行块插件 ${name} - 开始`);
contentLines.push(...content, '')
console.log(`[info] 执行块插件 ${name} - 结束`);
console.log('')
})
return contentLines
}
}

0 comments on commit 7f9d289

Please sign in to comment.