目录
Please enable Javascript to view the contents

Git 中文名乱码导致 cloc 统计代码量出错

 ·  ☕ 2 分钟

重要

core.quotepath 默认值为 true,Git 会将路径中的非 ASCII 字符转义为八进制编码(\346\265\213...)。

cloc 通过 git diff 获取文件列表时,收到的是转义后的路径,无法在仓库中找到对应文件,导致报错。core.quotepath 设为 false 让 Git 原样输出中文路径即可。

环境说明

  • Ubuntu 18.04
  • cloc(apt 安装,版本较老;如需最新版见 Release

1.简介

需求:按周统计代码增量,用于衡量外包团队工作量。

涉及三个子问题:

问题方案
用什么工具cloc(Count Lines of Code)
如何统计最近一周增量git log --after 获取起始 commit,cloc --git --diff 对比
中文文件名报错git config --global core.quotepath false

2.说明

2.1 安装 cloc

1
sudo apt install cloc

2.2 统计一周代码增量

核心思路:找到 7 天前的 commit,再用 cloc 对比该 commit 与当前 HEAD。

1
2
3
4
5
date_str=$(date --date="1 weeks ago" +"%Y-%m-%d")
logs=$(git log --after="${date_str}" --pretty=format:"%h")

# 取最早的一条与 HEAD 做 diff
cloc --git --diff "${logs##*$'\n'}" HEAD
参数说明
--date="1 weeks ago"取 7 天前的日期
--after过滤指定日期之后的 commit
--pretty=format:"%h"只输出 commit 短 ID
"${logs##*$'\n'}"bash 参数扩展,取最后一行(最早的一条 commit)

2.3 中文文件名报错与修复

仓库中存在中文文件名时,cloc 报错:

1
2
3
$ cloc --git --diff c9df9mf09df HEAD
fatal: pathspec '"road/Road/\346\265\213\350\257\225\345\234\271\2.sql"' did not match any files
Failed to create tarfile of files from git. at /usr/bin/cloc line 3811.

报错链路:

1
2
3
4
5
Git 输出路径(core.quotepath=true)
  → 中文被转义为八进制编码(\346\265\213...)
  → cloc 拿到转义后的路径传给 git diff
  → git 在仓库中找不到这个转义路径对应的文件
  → fatal: pathspec did not match any files

修复:

1
git config --global core.quotepath false

core.quotepath 控制 Git 输出路径时是否转义非 ASCII 字符:

行为效果
true(默认)路径中的中文被转义为 \346\265\213...cloc 无法匹配文件
false路径原样输出中文cloc 正常工作

2.4 定时自动统计(cron)

1
2
3
4
5
# 每周一凌晨统计上一周的代码增量
0 0 * * 1 cd /path/to/repo && \
  date_str=$(date --date="1 weeks ago" +"%Y-%m-%d") && \
  first_commit=$(git log --after="${date_str}" --reverse -1 --pretty=format:"%h") && \
  cloc --git --diff "${first_commit}" HEAD

3.总结

  1. cloc 通过 git 获取文件列表时,依赖 Git 输出的路径可被 git 自身识别;
  2. core.quotepath=true 将中文转义为八进制编码,破坏了路径的可识别性;
  3. core.quotepath 设为 false 后,Git 原样输出中文路径,cloc 正常工作。

4.参考

分享

Hex
作者
Hex
CloudNative Developer