You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ruby版Github-Linguist批量获取GitHub在线仓库语言统计数据

报错根因

Rugged::Repository.new 仅支持加载本地文件系统中已存在的Git仓库,不支持直接传入远程GitHub仓库的HTTP/HTTPS地址,这是运行代码报错的核心原因。

可行实现方案

方案1:临时克隆远程仓库分析(与本地运行Linguist结果完全一致)

该方案统计逻辑与你本地运行Linguist的规则100%对齐,输出结果完全一致。
首先执行命令安装依赖:
gem install rugged linguist tmpdir fileutils
参考实现代码:

require 'rugged'
require 'linguist'
require 'tmpdir'
require 'fileutils'

# 替换为目标远程GitHub仓库地址
remote_repo_url = "https://github.com/目标用户名/目标仓库名.git"

# 自动创建临时目录存储克隆文件,分析完成后自动删除
Dir.mktmpdir do |tmp_dir|
  # 仅拉取最新提交,减少克隆耗时
  repo = Rugged::Repository.clone_at(remote_repo_url, tmp_dir, depth: 1)
  project = Linguist::Repository.new(repo, repo.head.target_id)

  # 输出统计结果
  puts "主语言:#{project.language}"
  puts "语言占比统计:"
  total_bytes = project.languages.values.sum
  project.languages.each do |lang, byte_count|
    percentage = (byte_count.to_f / total_bytes * 100).round(2)
    puts "- #{lang}:#{percentage}%(#{byte_count} 字节)"
  end
end

如果需要分析私有仓库,在clone_at方法中添加认证参数即可:

repo = Rugged::Repository.clone_at(remote_repo_url, tmp_dir, 
  depth: 1,
  credentials: Rugged::Credentials::UserPassword.new(
    username: "你的GitHub用户名",
    password: "你的GitHub个人访问令牌"
  )
)

方案2:调用GitHub公开API获取语言统计(无需克隆仓库)

GitHub已默认使用Linguist统计所有公开仓库的语言数据,直接调用API即可获取结果,无需克隆仓库,也不需要安装rugged、linguist依赖。
参考实现代码:

require 'net/http'
require 'json'

# 替换为目标仓库的所有者用户名和仓库名
repo_owner = "目标用户名"
repo_name = "目标仓库名"

uri = URI("https://api.github.com/repos/#{repo_owner}/#{repo_name}/languages")
response = Net::HTTP.get_response(uri)

if response.code == "200"
  lang_data = JSON.parse(response.body)
  total_bytes = lang_data.values.sum
  puts "语言占比统计:"
  lang_data.each do |lang, byte_count|
    percentage = (byte_count.to_f / total_bytes * 100).round(2)
    puts "- #{lang}:#{percentage}%(#{byte_count} 字节)"
  end
else
  puts "请求失败,错误码:#{response.code}"
end

如果需要访问私有仓库,在请求头中添加GitHub个人访问令牌即可。

内容的提问来源于stack exchange,提问作者shaishav maisuria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:57:03