Search code examples
node.jsgitbitbucketgit-commitnodegit

nodegit avoid creating empty commit nodejs bitbucket


I am using following code to create a commit using nodegit library of nodejs

function createCommit(commitMsg) {
  console.log("Creating commit");
  let repository, index, oid, author, committer;
  return NodeGit.Repository.open(bb.repoPath)
    .then(function (repo) {
      repository = repo;
      return repository.refreshIndex();
    })
    .then(function (idx) {
      index = idx;
      const entryCount = index.entryCount();
      console.log("file: nodegit.js:74 ~ entryCount:", entryCount);
      if (entryCount === 0) {
        console.log("No changes to commit.");
        return;
      }
      return index.addAll();
    })
    .then(function () {
      return index.write();
    })
    .then(function () {
      return index.writeTree();
    })
    .then(async function (oidResult) {
      const head = await NodeGit.Reference.nameToId(repository, "HEAD"); // get reference to the current state
      const parent = await repository.getCommit(head); // get the commit for current state
      oid = oidResult;
      author = NodeGit.Signature.now(bb.name, bb.email);
      committer = NodeGit.Signature.now(bb.name, bb.email);
      return repository.createCommit("HEAD", author, committer, commitMsg, oid, [parent]);
    })
    .then(function (info) {
      console.log("Commit created successfully!");
      return info;
    })
    .catch((err) => {
      console.log("Error creating commit:", err);
      throw err;
    });
}

I am checking the entryCount as well

      const entryCount = index.entryCount();
      console.log("file: nodegit.js:74 ~ entryCount:", entryCount);
      if (entryCount === 0) {
        console.log("No changes to commit.");
        return;
      }

but even if there is no file to commit it shows >0 entryCount.

I tried

git reset --hard

still there is entry count and makes an empty commit.

What can be the issue? is there any other solution?


Solution

  • By checking the number of files to commit we can avoid empty commits

    function getChangesCount() {
      return NodeGit.Repository.open(bb.repoPath)
        .then(repository => {
          return repository.getStatus();
        })
        .then(statuses => {
          return statuses.length;
        }).catch(error => {
          console.error(error);
          return null;
        });
    }