Created
December 25, 2021 22:02
-
-
Save mhsattarian/ab9d1e0077a90f3588c8d92ea7d9f7a9 to your computer and use it in GitHub Desktop.
Get a file [git] contributors (blame) using node-git
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const git = require('nodegit'); | |
const pathToRepo = require("path").resolve("./.git"); | |
const uniqBy = require('../../utils').uniqBy | |
let $repo = null; | |
/** Blame last file change | using commit id */ | |
async function blameLast_old(filePath, callback) { | |
const repo = $repo ? $repo : await git.Repository.open(pathToRepo); | |
const blame = await git.Blame.file(repo, filePath.slice(2)); | |
const oid = blame.getHunkByIndex(blame.getHunkCount() - 1).origCommitId(); | |
const commit = await git.Commit.lookup(repo, oid); | |
const email = commit.author().email(); | |
const time = commit.time() * 1000 | |
callback(null, { email: email, time }); | |
} | |
/** Blame last file change */ | |
async function blameLast(filePath, callback) { | |
const repo = $repo ? $repo : await git.Repository.open(pathToRepo); | |
const blame = await git.Blame.file(repo, filePath.slice(2)); | |
const hunk = blame.getHunkByIndex(blame.getHunkCount() - 1); | |
const email = hunk.finalSignature().email(); | |
const time = hunk.finalSignature().when().time() * 1000; | |
callback(null, { email: email, time }); | |
} | |
async function blameAll(filePath, callback) { | |
const repo = $repo ? $repo : await git.Repository.open(pathToRepo); | |
const blame = await git.Blame.file(repo, filePath.slice(2)); | |
const hunks = Array(blame.getHunkCount()).fill().map((_, idx) => blame.getHunkByIndex(idx)); | |
const contributors = hunks.map(hunk => { | |
const email = hunk.finalSignature().email(); | |
const time = hunk.finalSignature().when().time() * 1000; | |
return { email, time } | |
}); | |
const uniqeContributors = uniqBy(contributors, (i) => i.email); | |
callback(null, uniqeContributors); | |
} | |
module.exports = { blameLast, blameAll }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment