RubyFlogFlay配置Skill ruby-flog-flay-setup

这个技能用于在Ruby项目中自动化设置代码复杂度检查(flog)和重复代码检测(flay),包括配置Rake任务和git pre-commit钩子,以提升代码质量和开发效率。关键词:Ruby, 代码复杂度, 重复代码, Flog, Flay, Rake, pre-commit, 自动化测试, 代码质量检查。

测试 0 次安装 0 次浏览 更新于 3/19/2026

name: ruby-flog-flay-setup description: 为 Ruby 项目安装标准化的 flog/flay Rake 任务和运行 bundle exec rake 的 pre-commit 钩子。用于添加或规范化代码复杂性和重复检查时。

Ruby Flog Flay 设置

概述

安装具有环境可配置阈值的 flog/flay Rake 任务和运行 bundle exec rake 的 pre-commit 钩子。

工作流程

1) 检查现有设置

  • 检查 Gemfile 中是否有 flogflay 条目。
  • 搜索 Rakefilerakelib/ 中现有的 :flog:flay rake 任务,以避免重复。
  • 检查 git config core.hooksPath 以确定钩子目录(未设置时默认是 .git/hooks)。

2) 确保依赖项

  • 如果缺少,在 Gemfile 中添加 gem "flay"gem "flog"(不固定版本)。
  • 如果需要,运行 bundle install

3) 在 Rakefile 中定义任务

  • 直接在 Rakefile 中定义 :flog:flay 任务。
  • 使用带有默认值的环境可配置阈值。
  • 为两个工具使用 bundle exec
  • 仅在失败时使用 puts 记录并退出非零;成功时保持静默。
  • 不要过滤任何文件或路径。
  • 允许 flay 重复当 总分数 <= FLAY_THRESHOLD

示例任务定义:

desc "运行 flog"
task :flog do
  output = `bundle exec flog -a lib`
  threshold = (ENV["FLOG_THRESHOLD"] || 25).to_i
  method_scores = []

  output.each_line do |line|
    if line =~ /^\s*(\d+\.\d+):\s+(.+#.+)\s+(.+\.rb)/
      score = $1.to_f
      method_name = $2.strip
      file_path = $3.strip
      method_scores << [score, "#{method_name} #{file_path}"]
    end
  end

  failing_methods = method_scores.select { |score, _| score > threshold }
  if failing_methods.any?
    puts "
Flog 失败: 复杂性分数 > #{threshold} 的方法:"
    failing_methods.each { |score, method_name| puts "  #{score}: #{method_name}" }
    exit 1
  end
end

desc "运行 flay"
task :flay do
  output = `bundle exec flay lib`
  threshold = (ENV["FLAY_THRESHOLD"] || 0).to_i

  if (match = output.match(/Total score \(lower is better\) = (\d+)/))
    score = match[1].to_i
    if score > threshold
      puts "
Flay 失败: 总重复分数是 #{score}, 必须 <= #{threshold}"
      puts output
      exit 1
    end
  end
end
  • 移除或更新 rakelib/ 中任何冲突的 :flog/:flay 任务,以避免重复定义。
  • 如果项目期望在 CI 中运行,确保默认任务包括 flogflay

4) 安装 pre-commit 钩子

  • core.hooksPath(或 .git/hooks)的钩子目录中创建或更新 pre-commit
  • 使用 bash 并无条件运行 bundle exec rake
  • 如果 rake 失败,退出非零。

示例钩子:

#!/usr/bin/env bash
bundle exec rake
result=$?
if [ $result -ne 0 ]; then
  echo "bundle exec rake 失败。提交已中止。"
  exit $result
fi
  • 确保钩子可执行。

5) 验证

  • 运行 bundle exec rake 并确认它成功。
  • 如果需要,进行测试提交以确认钩子阻止失败的构建。