7

使用 Node-git 我只想:

  1. 打开一个仓库(文件已被写入/更新的地方)
  2. 暂存文件
  3. 做承诺

使用 git cli 我会写这样的东西

cd repo    
git add file.js
git commit -m "Added file.js"

我正在尝试按照此处描述如何使用 nodegit 执行此操作的示例,但很难遵循这些代码行:

.then(function() {
  return repo.refreshIndex();
})
.then(function(indexResult) {
  index = indexResult;
})
.then(function() {
  // this file is in the root of the directory and doesn't need a full path
  return index.addByPath(fileName);
})
.then(function() {
  // this file is in a subdirectory and can use a relative path
  return index.addByPath(path.join(directoryName, fileName));
})
.then(function() {
  // this will write both files to the index
  return index.write();
})
.then(function() {
  return index.writeTree();
})
.then(function(oidResult) {
  oid = oidResult;
  return nodegit.Reference.nameToId(repo, "HEAD");
})
.then(function(head) {
  return repo.getCommit(head);
})
.then(function(parent) {
  var author = nodegit.Signature.create("Scott Chacon",
    "schacon@gmail.com", 123456789, 60);
  var committer = nodegit.Signature.create("Scott A Chacon",
    "scott@github.com", 987654321, 90);

  return repo.createCommit("HEAD", author, committer, "message", oid, [parent]);
})
.done(function(commitId) {
  console.log("New Commit: ", commitId);
});

有必要这么长吗?repo.refreshIndex()、index.write()、index.writeTree()等的作用是什么?API 文档对初学者不太友好。

感谢开导!

4

1 回答 1

4

这是我第一次使用这个库,但我想我还是会回答的。如果您将 promise 换成await. 我用我对正在发生的事情的基本理解发表了评论。

  const repo = await git.Repository.open(localNotesDir);
  const index = await repo.refreshIndex(); // read latest
  const files = await repo.getStatus(); // get status of all files
  files.forEach(file => index.addByPath(file.path())); // stage each file
  await index.write(); // flush changes to index
  const changes = await index.writeTree(); // get reference to a set of changes
  const head = await git.Reference.nameToId(repo, "HEAD"); // get reference to the current state
  const parent = await repo.getCommit(head); // get the commit for current state
  const author = git.Signature.now("Scott Chacon", "schacon@gmail.com"); // build auth/committer
  const committer = git.Signature.now("Scott A Chacon", "scott@github.com");
  // combine all info into commit and return hash
  const commitId = await repo.createCommit("HEAD", author, committer, "message", changes, [parent]);
  console.log('commitId', commitId);
  // changes and head are each oids. Read about them here:
  // https://hackage.haskell.org/package/gitlib-0.6.5/docs/Data-Git-Oid.html
于 2020-02-25T05:12:15.693 回答