nodegit得到所有分阶段文件的差异

NodeGit提供了一个简单的方法来获取所有当前更改的差异,而无需进行阶段性更改:

import NodeGit, { Diff } from 'nodegit'; function getUnstagedChanges(path) { const repo = await NodeGit.Repository.open(path); const diff = await Diff.indexToWorkdir(repo, null, { flags: Diff.OPTION.INCLUDE_UNTRACKED | Diff.OPTION.RECURSE_UNTRACKED_DIRS }); console.log(await diff.patches()); } getUnstagedChanges(); 

是否有类似的解决scheme来获得所有阶段性变化的差异?

好的,我find了一种方法 – 但是在第一次提交之前它不会工作:

 import NodeGit, { Diff } from 'nodegit'; function getStagedChanges(path) { const repo = await NodeGit.Repository.open(path); const head = await repository.getHeadCommit(); if (!head) { return []; } const diff = await Diff.treeToIndex(repo, await head.getTree(), null); const patches = await diff.patches(); console.log(patches.map((patch) => patch.newFile().path())); } getStagedChanges(); 

奇怪的是,你没有看到分阶段的变化,因为indexToWorkdir工作方式就像git diff ,只显示阶段性的变化。 我写了一个例子,这对我很有用。 它显示diff和stageaging和unstaged文件,请尝试它。 如果跳过选项,则只显示分段文件。

还要注意将Diff.OPTION.SHOW_UNTRACKED_CONTENTreplace为Diff.OPTION.SHOW_UNTRACKED_CONTENT

 import path from 'path'; import Git from 'nodegit'; async function print() { const repo = await Git.Repository.open(path.resolve(__dirname, '.git')); const diff = await Git.Diff.indexToWorkdir(repo, null, { flags: Git.Diff.OPTION.SHOW_UNTRACKED_CONTENT | Git.Diff.OPTION.RECURSE_UNTRACKED_DIRS }); // you can't simple log diff here, it logs as empty object // console.log(diff); // -> {} diff.patches().then((patches) => { patches.forEach((patch) => { patch.hunks().then((hunks) => { hunks.forEach((hunk) => { hunk.lines().then((lines) => { console.log("diff", patch.oldFile().path(), patch.newFile().path()); console.log(hunk.header().trim()); lines.forEach((line) => { console.log(String.fromCharCode(line.origin()) + line.content().trim()); }); }); }); }); }); }); return diff; } print().catch(err => console.error(err));