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中是否有flog和flay条目。 - 搜索
Rakefile和rakelib/中现有的:flog或:flayrake 任务,以避免重复。 - 检查
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 中运行,确保默认任务包括
flog和flay。
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并确认它成功。 - 如果需要,进行测试提交以确认钩子阻止失败的构建。