我正在创建一个 Node JS 脚本,它需要从存储库中获取所有 Git 标签,以及创建标签的消息和日期,然后将它们保存为 JSON 文件中的条目。例如:
[{
"tag": "v1.1.0",
"message": "Add navigation",
"date": "Tue Oct 4 10:19:12 2018 +0100"
}, {
"tag": "v1.1.1",
"message": "Fix issue with spacing in the navigation",
"date": "Tue Oct 9 12:13:16 2018 +0100"
}]
我已经想出了怎么做,使用一些 Node 模块来访问标签,然后执行一些 Git 命令从每个标签中获取我需要的所有信息。这是使用 shelljs 完成的.
我遇到的问题是速度非常慢。运行 gitTag.all((tags) = {})
(使用 git-tag )很快,因为它只提取标签名称。但是,为了获取消息和日期,我在一个循环中为每个标签运行两个单独的命令:
let msg = shell.exec(`git for-each-ref refs/tags/${tag} --format='%(subject)'`, {silent:true}).stdout;
let date = shell.exec(`git for-each-ref refs/tags/${tag} --format='%(authordate)'`, {silent:true}).stdout;
这两个命令无论如何都有点慢,但是每次为每个标签名称运行它们需要很长时间。
有没有更快的方法让我做到这一点?
请记住,我正在同步运行它,因为另一个 Node 脚本将读取此 JSON 文件,这可能会导致竞争条件。但是,如果任何异步想法也能解决这个问题,我们也欢迎。
请查看我的下面的完整代码:
const gitTag = require('git-tag')({
localOnly: true,
dir: '.git'
});
const fs = require('fs-extra');
const shell = require('shelljs');
let tagsAllData = [];
let formatString = (string) => {
return string.replace(/^'/, '').replace(/'\n+$/, '');
}
// Fetch all git tags
gitTag.all((tags) => {
tags.forEach(tag => {
// Collect the tag message and date values
let msg = shell.exec(`git for-each-ref refs/tags/${tag} --format='%(subject)'`, {silent:true}).stdout;
let date = shell.exec(`git for-each-ref refs/tags/${tag} --format='%(authordate)'`, {silent:true}).stdout;
// Create array of tag objects
tagsAllData.push({
'tag': tag,
'message': formatString(msg),
'date': formatString(date)
});
});
// Write the tag data as a JSON file
let tagsJSON = JSON.parse(JSON.stringify(tagsAllData));
fs.writeJSONSync('src/data/tags.json', tagsJSON);
});
最佳答案
您的实际代码为每个标记调用 shell 两次。为了加快速度,您应该调用 shell,因此 git 最多调用一次 - 对于 all 标记。在 shell 中,它看起来像这样:
git for-each-ref --sort=v:refname --format "tag: %(refname:strip=2) message: %(subject) date: %(creatordate:iso)" refs/tags
输出看起来像这样:
tag: v2.20.0-rc0 message: Git 2.20-rc0 date: 2018-11-18 18:25:38 +0900
tag: v2.20.0-rc1 message: Git 2.20-rc1 date: 2018-11-21 23:25:15 +0900
tag: v2.20.0-rc2 message: Git 2.20-rc2 date: 2018-12-01 21:45:08 +0900
tag: v2.20.1 message: Git 2.20.1 date: 2018-12-15 12:31:46 +0900
您必须首先将此输出拆分为单独的行,然后将每行拆分为字段。您可以通过调整 format
使解析更容易(例如,通过在字段之间使用特殊字符)来简化此过程。
关于javascript - 我在 Node JS 中检索 Git 标签信息的方法很慢,如何加快速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040061/