Skip to content

Instantly share code, notes, and snippets.

@schacon
Created April 12, 2025 00:41
Show Gist options
  • Save schacon/827b79b0d9dd9940d34b780e78367b92 to your computer and use it in GitHub Desktop.
Save schacon/827b79b0d9dd9940d34b780e78367b92 to your computer and use it in GitHub Desktop.
ruby script using Rugged to count the number of trailer keys in use
#!/usr/bin/env ruby
require 'rugged'
require 'optparse'
# Parse command line options
options = {
repo_path: '.',
branch: 'main'
}
OptionParser.new do |opts|
opts.banner = "Usage: trailer_counter.rb [options]"
opts.on("-r", "--repo PATH", "Path to git repository") do |repo_path|
options[:repo_path] = repo_path
end
opts.on("-b", "--branch BRANCH", "Branch to analyze (default: main)") do |branch|
options[:branch] = branch
end
opts.on("-h", "--help", "Show this help message") do
puts opts
exit
end
end.parse!
begin
# Open the repository
repo = Rugged::Repository.new(options[:repo_path])
# Set up the counter for trailer keys
trailer_counts = Hash.new(0)
commit_count = 0
# Set up a walker to go through all commits in the branch
walker = Rugged::Walker.new(repo)
# Get the branch reference
branch_ref = repo.references["refs/heads/#{options[:branch]}"]
if branch_ref.nil?
puts "Error: Branch '#{options[:branch]}' not found"
exit 1
end
# Push the branch head to the walker
walker.push(branch_ref.target_id)
# Walk through all commits
walker.each do |commit|
commit_count += 1
# Extract trailers from the commit message
trailers = commit.trailers
# Count each trailer key
trailers.each do |key, value|
trailer_counts[key.downcase] += 1
end
end
# Print results
puts "Analyzed #{commit_count} commits in branch '#{options[:branch]}'"
puts "\nTrailer Key Counts:"
puts "-" * 30
if trailer_counts.empty?
puts "No trailers found in commit messages"
else
# Sort by count (descending)
trailer_counts.sort_by { |_, count| -count }.each do |key, count|
puts "#{key}: #{count}"
end
end
rescue Rugged::RepositoryError => e
puts "Error: #{e.message}"
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment