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

How to implement a custom Rubocop rule for checking git branch naming convention?

例如,我需要检查 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 分析 code,作为 AST 节点,或文本行/整个文件。因此,答案是:有可能,但不要这样做。

我建议将这些东西分开,例如让 rake check 运行 rubocop 并运行 rake check_commits,后者会检查你的 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: