乘风破浪 激流勇进
你好!欢迎来看Tuziki's Planet !

利用AI大模型根据git commit记录自动生成工作报告脚本 reportByAI.js

首先要安装依赖 npm install node-fetch chalk ora yargs -D


package.json 里面顶部 要写 “type”: “module” , scripts里面 加上 “report”: “node generateWeeklyReportByAI.js”,


npm run report 默认生成本机用户的7天,即周报

npm run report – --m tutuhuang 生成指定用户的7天报告

npm run report – --d 13 生成近13天内本机用户报告

npm run report – --m tutuhuang --d 13 生成指定用户指定天数内报告

npm run report – --m all 生成所有用户7天数内报告


这里不建议一次打印所有用户太多天数的数据,ai处理不过来,会断开


将以下代码保存为generateWeeklyReportByAI.js存放在项目根目录


执行npm run report 完成之后,可以在根目录看到 weekly_report.md文件,打开vscode预览模式,即可阅读报告


如果想对报告做一些要求和调整可以在文案content里面修改


import { execSync } from 'child_process'
import fs from 'fs'
import path from 'path'
import fetch from 'node-fetch'
import chalk from 'chalk'
import ora from 'ora'
import { userInfo } from 'os'
import yargs from 'yargs'

const { username } = userInfo()
console.log(`当前用户名为: ${username}`)

// 获取最近几天的 Git 提交记录
function getGitLog(days = 7) {
  const since = `--since="${days} days ago"`
  const format = '--pretty=format:"%h - %an, %ar : %s%n%b"'
  const log = execSync(`git log ${since} ${format}`).toString()
  return log
}

// 解析 Git 日志,按作者归类
function parseGitLog(log) {
  const commitsByAuthor = {}
  const lines = log.split('\n')

  lines.forEach((line) => {
    if (line.includes('Merge')) return // 跳过包含 "Merge" 关键字的提交记录

    const match = line.match(/- (.+?), (.+?) : (.+)/)
    if (match) {
      const author = match[1]
      const commit = match[3]
      if (!commitsByAuthor[author]) {
        commitsByAuthor[author] = []
      }
      commitsByAuthor[author].push(commit)
    } else if (line.trim() && Object.keys(commitsByAuthor).length > 0) {
      const lastAuthor = Object.keys(commitsByAuthor).pop()
      commitsByAuthor[lastAuthor][commitsByAuthor[lastAuthor].length - 1] += `\n  ${line.trim()}`
    }
  })

  return commitsByAuthor
}

// 调用接口处理提交记录
async function processCommitsByAuthor(author, commits) {
  const content =
    `要将这些更改归类和合并为简化的开发报告,可以将相关的功能改进、模块重构和问题修复分类并合并,:\n${commits.join('\n')}`.replace(
      /\n/g,
      '\\n'
    ) // 将换行符转换为 \n

  const response = await fetch('https://www.ai.com:9999/api/assistant/chat', {
    headers: {
      accept: '*/*',
      'accept-language': 'en-US',
      'content-type': 'application/json',
      priority: 'u=1, i',
      'sec-ch-ua': '"Not;A=Brand";v="24", "Chromium";v="128"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': '"Windows"',
      'sec-fetch-dest': 'empty',
      'sec-fetch-mode': 'cors',
      'sec-fetch-site': 'cross-site',
    },
    referrerPolicy: 'strict-origin-when-cross-origin',
    body: JSON.stringify({
      content: content,
      function_code: 'intelligentQA',
      model: 'qwen2.5-coder:14b',
      uid: username,
    }),
    method: 'POST',
    mode: 'cors',
    credentials: 'omit',
  })

  const result = await response.text()

  const lines = result.split('\n')
  let finalContent = ''
  lines.forEach((line) => {
    try {
      const json = JSON.parse(line)
      if (json.data && json.data.content) {
        finalContent += json.data.content
      }
    } catch (e) {
      // 忽略解析错误
    }
  })

  return finalContent
}

// 生成 Markdown 格式的周报
async function generateWeeklyReport(commitsByAuthor, days) {
  let report = `# 工作报告\n\n## 最近${days}天的Git提交记录AI总结\n\n`

  for (const author in commitsByAuthor) {
    report += `### ${author}\n`
    const processedCommits = await processCommitsByAuthor(author, commitsByAuthor[author])
    report += `${processedCommits}\n\n`
  }

  return report
}

// 保存周报到文件
function saveReport(report, filename = 'weekly_report.md') {
  const filePath = path.join(process.cwd(), filename)
  fs.writeFileSync(filePath, report)
  console.log(chalk.green(`周报已生成: ${filePath}`))
}

// 主函数
async function main() {
  const argv = yargs(process.argv.slice(2))
    .option('days', {
      alias: 'd',
      type: 'number',
      description: '获取最近几天的提交记录',
      default: 7,
    })
    .option('member', {
      alias: 'm',
      type: 'string',
      description: '指定用户的提交记录,使用 "all" 获取所有用户的提交记录',
    })
    .help()
    .parse()

  const { days, member } = argv
  // console.log('===', days, member) // 添加调试信息,确认参数解析正确
  const includeAllAuthors = member === 'all'
  const specifiedUser = member || username

  const spinner = ora(chalk.blue('提取Git记录中...')).start()
  const log = getGitLog(days)
  spinner.succeed(chalk.green('Git记录提取完成'))

  spinner.start(chalk.blue('解析Git记录中...'))
  const allCommitsByAuthor = parseGitLog(log)
  spinner.succeed(chalk.green('Git记录解析完成'))

  // 打印所有作者名
  const authors = Object.keys(allCommitsByAuthor).join(', ')
  console.log(chalk.yellow(`ℹ️  检测到该项目近${days}天有以下作者提交:`), authors)

  // 打印当前处理的用户和天数信息
  console.log(chalk.blue(`ℹ️  当前打印的是 ${specifiedUser} 的 ${days} 天的数据`))

  // 根据用户输入的参数进行过滤
  let commitsByAuthor
  if (includeAllAuthors) {
    commitsByAuthor = allCommitsByAuthor
  } else {
    commitsByAuthor = {}
    for (const author in allCommitsByAuthor) {
      if (author.includes(specifiedUser)) {
        commitsByAuthor[author] = allCommitsByAuthor[author]
      }
    }
  }

  spinner.start(chalk.blue('用AI润色合并优化中...'))
  const report = await generateWeeklyReport(commitsByAuthor, days)
  spinner.succeed(chalk.green('AI润色合并优化完成'))

  spinner.start(chalk.blue('生成报告中...'))
  saveReport(report)
  spinner.succeed(chalk.green('报告生成完成'))
}

main()



返回列表
返回顶部←