git-history/cli/git.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-02-10 05:21:05 +03:00
const execa = require("execa");
2019-02-18 21:09:32 +03:00
const pather = require("path");
2019-02-10 05:21:05 +03:00
2019-02-18 22:06:59 +03:00
async function getCommits(path, last, before) {
const format = `{"hash":"%h","author":{"login":"%aN"},"date":"%ad"},`;
2019-02-18 22:06:59 +03:00
const { stdout } = await execa(
"git",
[
"log",
`--max-count=${before ? last + 1 : last}`,
`--pretty=format:${format}`,
"--date=iso",
`${before || "HEAD"}`,
"--",
pather.basename(path)
],
{ cwd: pather.dirname(path) }
);
2019-02-10 05:21:05 +03:00
const json = `[${stdout.slice(0, -1)}]`;
2019-02-18 22:06:59 +03:00
const messagesOutput = await execa(
"git",
[
"log",
`--max-count=${last}`,
`--pretty=format:%s`,
`${before || "HEAD"}`,
"--",
pather.basename(path)
],
{ cwd: pather.dirname(path) }
);
const messages = messagesOutput.stdout.replace('"', '\\"').split(/\r?\n/);
2019-02-18 22:06:59 +03:00
const result = JSON.parse(json).map((commit, i) => ({
...commit,
date: new Date(commit.date),
message: messages[i]
}));
2019-02-18 22:06:59 +03:00
return before ? result.slice(1) : result;
2019-02-10 05:21:05 +03:00
}
async function getContent(commit, path) {
2019-02-18 21:09:32 +03:00
const { stdout } = await execa(
"git",
["show", `${commit.hash}:./${pather.basename(path)}`],
{ cwd: pather.dirname(path) }
);
2019-02-10 05:21:05 +03:00
return stdout;
}
2019-02-18 22:06:59 +03:00
module.exports = async function(path, last, before) {
const commits = await getCommits(path, last, before);
2019-02-10 05:21:05 +03:00
await Promise.all(
commits.map(async commit => {
commit.content = await getContent(commit, path);
})
);
return commits;
};