Nodegit - 如何暂存和提交文件? (简单的例子!)

时间:2017-12-03 16:02:53

标签: git nodegit

使用Node-git我只想:

  1. 打开一个仓库(文件已被写入/更新)
  2. 暂存文件
  3. 提交
  4. 使用git cli我会写这样的东西

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

    我试图按照示例here描述如何使用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-docs不是那么初学者友好。

    感谢启蒙!

2 个答案:

答案 0 :(得分:2)

这是我第一次使用此库,但我还是想回答。如果您放弃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

答案 1 :(得分:0)

即使我正在为自己的用例探索nodegit。显然,我认为您可以在这里找到解决问题的方法。 https://github.com/nodegit/nodegit/tree/master/examples