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

如何在R脚本中获取git shortlog -s -n输出并用于后续处理?

在R中获取git shortlog输出的解决方案

核心前提确认

先确保两个关键条件满足:

  • git可被R调用:执行system2("git", "--version", stdout=TRUE),应返回git版本信息,否则需将git所在路径加入系统环境变量
  • 操作路径为git仓库:指定的目录需是git仓库根目录,可通过git status验证

方法1:用system2()正确捕获输出

system2()需同时设置stdout=TRUE和stderr=TRUE(便于排查错误),并通过wd参数指定git仓库路径(当前工作目录是仓库则可省略):

# 替换为你的git仓库路径
repo_path <- "/path/to/your/git/repo"
shortlog_result <- system2(
  command = "git",
  args = c("shortlog", "-s", "-n"),
  stdout = TRUE,
  stderr = TRUE,
  wd = repo_path
)

# 查看输出结果
print(shortlog_result)

如果执行出错,shortlog_result会返回错误提示(比如"not a git repository"),帮你定位问题。


方法2:用{sys}包的exec_internal()获取输出

sys::exec_wait()仅返回退出状态码,而exec_internal()会捕获标准输出和错误输出,适合精细化处理:

library(sys)

repo_path <- "/path/to/your/git/repo"
exec_result <- sys::exec_internal(
  command = "git",
  args = c("shortlog", "-s", "-n"),
  wd = repo_path
)

# 将二进制输出转为文本并处理成行列表
shortlog_text <- rawToChar(exec_result$stdout)
shortlog_lines <- strsplit(shortlog_text, "\n")[[1]]
# 过滤空行
shortlog_lines <- shortlog_lines[shortlog_lines != ""]

# 输出结果
print(shortlog_lines)

后续数据处理示例

拿到输出后,可进一步解析提交统计数据:

# 拆分每行的提交次数和作者名
parsed_data <- lapply(shortlog_lines, function(line) {
  parts <- strsplit(line, "\\s+", n=2)[[1]]
  list(commits = as.integer(parts[1]), author = parts[2])
})

# 转成数据框便于后续分析
commit_df <- do.call(rbind, lapply(parsed_data, data.frame))
print(commit_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:37:02