如何实现用于检查git分支命名约定的自定义Rubocop规则



例如,我需要检查git分支命名的正确性-它应该包含类似于以下的票证ID:

module Rails
class GitBranchName < RuboCop::Cop::Cop
MSG = "Use correct branch name by pattern  '{TicketID}-{Description}'. TicketID is mandatory for linking with the task tracker and should be at least 2 digits"
def on_send(node = nil)
branch = `git rev-parse --abbrev-ref HEAD`
return if starts_from_ticket_number?(branch)
p "Current branch name: '#{branch}'"
# add_offense(node, severity: :warning)
end
private
def starts_from_ticket_number?(name)
gitflow_prefixes = [:bug, :bugfix, :feature, :fix, :hotfix, :origin, :release, :wip]
name.match?(/(#{gitflow_prefixes.join('/|')})?d{2,}/)
end
end
end

但正如我所看到的,Rubocop只处理文本节点,只检查文本行。那么,是否可以定义一个只运行一次的规则来检查一个与代码无关但仅与业务逻辑相关的自定义检查?

我还在这里创建了讨论https://github.com/rubocop/rubocop/discussions/10470

正如您所指出的,rubocop分析代码,可以作为AST节点,也可以作为文本行/整个文件。因此,答案是:这可能,但不要这样做。

我建议将这些东西分开,例如,让运行rubocoprake check_commitsrake check,稍后检查您的git提交。

我最终添加了一个用于检查分支命名的自定义脚本,并将其添加到CI管道中:

bin/git_check

#!/usr/bin/env ruby
# frozen_string_literal: true
# :nocov:
class GitBranchNameValidator
MSG = "Use correct branch name by pattern  '{TicketID}-{Description}'. TicketID is mandatory for linking with the task tracker and should be at least 2 digits"
class << self
def call
branch = `git rev-parse --abbrev-ref HEAD`.split("n").first
return if starts_from_ticket_number?(branch)
puts "Current branch name: '#{branch}'"
puts MSG
exit 1
end
private
def starts_from_ticket_number?(name)
gitflow_prefixes = [:bug, :bugfix, :feature, :fix, :hotfix, :origin, :release, :wip]
name.match?(/(#{gitflow_prefixes.join('/|')})?d{2,}/)
end
end
end
GitBranchNameValidator.call
# :nocov:

最新更新