使用 NodeJs 递归清理本地 Git 仓库

背景

由于常年混迹Github,所以在我电脑上有很多 clone 下的Git Repo,而这些 repo 使用中生成的临时文件占用了大量空间。粗略看了下空间占用,居然有23G。所以决定通过git clean命令把每一个仓库清理一下。但是先进入每一个仓库,然后执行上面的命令就太 low 了,于是决定写个脚本处理一下。最近 nodejs 用的多一些,因此决定用 nodejs 来处理这件事。

工作环境

我的电脑是 mac 系统,理论上这个解决方案也可以在 linux 和 win10 中的 linux 子系统中运行。

方案

解决思路

鉴于每个Git Repo的根目录中,都有一个名字叫做.git的文件夹。因此可以通过查找.git文件夹的位置,间接知道Git Repo的位置,类似下面这种:

1
2
3
/a/b/repo1/.git
/z/repo2.git
/repo3/.git

之后进入每个Git Repo,执行 git clean命令。

工具

  • NodeJs中的child_process。用于在 js 中执行unix系统的命令行程序
  • NodeJs中的path。用于处理路径
  • find命令。用于查找文件位置
  • cd命令。用于切换执行unix命令的目录位置
  • git命令。 用于执行git clean命令

步骤

1.找出所有.git文件夹的位置

通过child_process, 执行find . -type d -name .git命令,。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const process = require("child_process");

const find = process.spawn("find", ". -type d -name .git".split(" "));

find.stdout.on("data", data => {

// dirs中包含所有.git文件夹的位置
const dirs = data.toString().split(/\r?\n/));
});

find.stderr.on("data", data => {
console.log(`stderr: ${data}`);
});

find.on("close", code => {
console.log(`child process exited with code ${code}`);
});

最后得到的dirs是一个字符串数组,包含所有找到的.git文件夹的位置,类似['/a/b/repo1/.git', '/b/c/repo2/.git']

2.获得仓库位置

通过path获得.git目录所在Git Repo的路径

1
2
3
for (const i of dirs) {
const repo = path.dirname(i);
}

现在得到的repo变量中存储的就是Git Repo的路径

3.清理仓库

切换到repo目录,执行git clean -xdf 命令

1
2
3
4
5
6
7
8
9
10
11
12
const cleanRes = process.exec(
"cd " + repo + " && git clean -xdf .",
{},
(error, stdout, stderr) => {
console.log(`\nTry to clean up ${repo} by: '${cleanCommand}'`);
if (error) {
console.log(`error: ${error}`);
} else {
console.log(stdout);
}
}
);

结语

思路和解决方案都比较简单,本文仅作为记录。完整代码被我放到这里了。想要使用的同学可以把这个文件放到你要清理的文件夹下,然后用node执行即可。