首先通过sudo yum install libgit2-devel 安装库文件
#define COMMIT_OLD_ID "9bcc1bd3b27a514118ee7452edc0ddd18730df78" #define COMMIT_NEW_ID "1b885aba4c27661dd3e5270fe1d7e562b4224153" #include <iostream> #include <git2.h> typedef struct _code_node { int add; int delte; }code_node, *pcode_node; code_node code_num = {0}; int get_node_num(git_repository* repo, std::string commitIdA, std::string commitIdB) { // 获取两个提交的 OID(哈希) git_oid oldCommitId, newCommitId; int error = git_oid_fromstr(&oldCommitId, commitIdA.c_str()); git_oid_fromstr(&newCommitId, commitIdB.c_str()); // 检查提交是否存在 git_commit* oldCommit = nullptr; git_commit* newCommit = nullptr; error = git_commit_lookup(&oldCommit, repo, &oldCommitId); if (error != 0) { std::cerr << "Failed to lookup old commit: " << giterr_last()->message << std::endl; return 1; } error = git_commit_lookup(&newCommit, repo, &newCommitId); if (error != 0) { std::cerr << "Failed to lookup new commit: " << giterr_last()->message << std::endl; git_commit_free(oldCommit); return 1; } // 获取两个提交的树 git_tree* oldTree; git_tree* newTree; error = git_commit_tree(&oldTree, oldCommit); if (error != 0) { std::cerr << "Failed to get old tree: " << giterr_last()->message << std::endl; git_commit_free(oldCommit); git_commit_free(newCommit); return 1; } error = git_commit_tree(&newTree, newCommit); if (error != 0) { std::cerr << "Failed to get new tree: " << giterr_last()->message << std::endl; git_commit_free(oldCommit); git_commit_free(newCommit); return 1; } // 初始化差异选项 git_diff_options diffOpts = GIT_DIFF_OPTIONS_INIT; git_diff* diff = nullptr; error = git_diff_tree_to_tree(&diff, repo, oldTree, newTree, &diffOpts); if (error != 0) { std::cerr << "Failed to calculate diff: " << giterr_last()->message << std::endl; git_commit_free(oldCommit); git_commit_free(newCommit); return 1; } // 获取差异的统计信息 git_diff_stats* stats = nullptr; error = git_diff_get_stats(&stats, diff); if (error != 0) { std::cerr << "Failed to get diff stats: " << giterr_last()->message << std::endl; } else { code_num.add += git_diff_stats_insertions(stats); code_num.delte += git_diff_stats_deletions(stats); // 释放统计信息 git_diff_stats_free(stats); } // 释放资源 git_diff_free(diff); git_commit_free(oldCommit); git_commit_free(newCommit); return 0; } int main() { git_libgit2_init(); // 打开或初始化 Git 存储库 git_repository* repo = nullptr; int error = git_repository_open(&repo, "/home/CodeHub/NetAnalysis"); if (error != 0) { std::cerr << "Failed to open repository: " << giterr_last()->message << std::endl; git_libgit2_shutdown(); return 1; } get_node_num(repo, COMMIT_OLD_ID, COMMIT_NEW_ID); std::cout << "Total additions: " << code_num.add << std::endl; std::cout << "Total deletions: " << code_num.delte << std::endl; git_repository_free(repo); git_libgit2_shutdown(); return 0; }
标签:node,git,int,代码,code,commit,message,统计 From: https://www.cnblogs.com/dandan520/p/17678434.html