node.jsbitbucketgit-commitgit-pushnodegit

nodegit bitbucket commit is not working properly nodejs


I am trying to push changes to bitbucket repo using nodegit npm package.

Here is the code

async function createCommit1(commitMsg) {
  try {
    const repo = await NodeGit.Repository.open(bb.repoPath);
    const index = await repo.refreshIndex(); // read latest
    const files = await repo.getStatus(); // get status of all files
    console.log("file: nodegit.js:212 ~ createCommit1 ~ files:", 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 NodeGit.Reference.nameToId(repo, "HEAD"); // get reference to the current state
    const parent = await repo.getCommit(head); // get the commit for current state
    const author = NodeGit.Signature.now(bb.name, bb.email); // build auth/committer
    const committer = NodeGit.Signature.now(bb.name, bb.email);
    // combine all info into commit and return hash
    const commitId = await repo.createCommit("HEAD", author, committer, commitMsg, changes, [parent]);
    console.log('commitId', commitId);
    return commitId;
  } catch (err) {
    console.log("file: nodegit.js:224 ~ createCommit1 ~ err:", err);
    throw err;

  }
}

function pushChanges1(commitMsg) {
  createCommit1(commitMsg)
    .then(() => {
      let repository;
      NodeGit.Repository.open(bb.repoPath)
        .then(function (repo) {
          repository = repo;
          return repository.getRemote("origin");
        })
        .then(function (remote) {
          return remote.push(
            ["refs/heads/main:refs/heads/main"],
            {
              callbacks: {
                credentials: function (_url, _userName) {
                  return NodeGit.Cred.userpassPlaintextNew(cred.userName, cred.password);
                }
              }
            }
          );
        })
        .then(() => {
          console.log("Local changes pushed successfully!");
        })
        .catch((err) => {
          console.log("file: nodegit.js:197 ~ pushChanges1 ~ err:", err);
          console.log("file: nodegit.js:199 ~ pushChanges1 ~ err.errno:", err.errno);
          if (err.errno === NodeGit.Error.CODE.EUPDFAIL) {
            // Push failed, pull changes
            console.log("Push failed, pulling changes...");
            return pullChanges3();
          } else if (err.errno === NodeGit.Error.CODE.ENOTFOUND) {
            // Remote branch not found, clone repository
            console.log("Remote branch not found, cloning repository...");
            return cloneRepo();
          } else {
            console.log("Error pushing changes:", err);
          }
        });
    });
}

it is making a commit and push (checked on bitbucket website as well) but not with the updated file content. And on VS code , same file is in staging and in changes.

What can be the issue?


Solution

  • finally got the solution and it is working

    function cloneRepo() {
      NodeGit.Clone.clone(bb.repoUrl, bb.repoPath, {
        fetchOpts: {
          callbacks: {
            credentials: function (_url, _userName) {
              return NodeGit.Cred.userpassPlaintextNew(cred.userName, cred.password);
            }
          }
        }
      })
        .then((repo) => {
          console.log("Repository cloned successfully!");
          return repo;
        })
        .catch((err) => {
          console.log("Error cloning repository:", err);
        });
    }
    
    function pullChanges() {
      console.log("Pulling Changes");
      let repository;
    
      return NodeGit.Repository.open(bb.repoPath)
        .then(function (repo) {
          repository = repo;
          return repository.fetchAll({
            callbacks: {
              credentials: function (_url, _userName) {
                return NodeGit.Cred.userpassPlaintextNew(cred.userName, cred.password);
              }
            }
          }, true);
        })
        .then(function () {
          return repository.mergeBranches("main", "origin/main");
        })
        .then(function () {
          console.log("Pull Done!");
          return "pull done";
        })
        .catch(function (err) {
          if (err.message.indexOf("Failed to open repository") !== -1) {
            // Repository does not exist, clone it
            console.log("Repository does not exist, cloning...");
            return cloneRepo();
          } else {
            console.log("Error fetching or merging changes:", err);
            throw err; // re-throw the error to propagate it to the caller
          }
        });
    }
    
    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;
        });
    }
    
    function pushChanges() {
      console.log("Trying push..");
      return NodeGit.Repository.open(bb.repoPath)
        .then(function (repo) {
          return repo.getRemote("origin");
        }).then(function (remote) {
          return remote.push(
            ["refs/heads/main:refs/heads/main"],
            {
              callbacks: {
                credentials: function (_url, _userName) {
                  return NodeGit.Cred.userpassPlaintextNew(cred.userName, cred.password);
                }
              }
            }
          );
        })
        .then(() => {
          console.log("Local changes pushed successfully!");
        }).catch((err) => {
          console.log("Push Failed...", err);
          throw err;
        });
    }
    
    async function syncRepo(commitMsg) {
      console.log("Syncing Repo :", commitMsg);
      try {
        await createCommit(commitMsg);
        // await createCommit1(commitMsg)
        pushChanges()
          .catch(async (err) => {
            console.log("file: nodegit.js:140 ~ syncRepo ~ err:", err.errno);
            if (err.errno === NodeGit.Error.CODE.ENONFASTFORWARD) {
              // Push failed, pull changes
              console.log("Push failed, pulling changes...");
              await pullChanges();
              await createCommit(commitMsg);
              return pushChanges();
            } else if (err.errno === NodeGit.Error.CODE.ENOTFOUND) {
              // Remote branch not found, clone repository
              console.log("Remote branch not found, cloning repository...");
              await cloneRepo();
              return syncRepo(commitMsg);
            } else {
              console.log("Error pushing changes:", err);
            }
          });
      } catch (err) {
        console.log("file: nodegit.js:276 ~ pushChanges1 ~ err:", err);
      }
    }
    
    const commitMsg = `4 commit - ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`;
    syncRepo(commitMsg);
    console.log("file: nodegit.js:324 ~ commitMsg:", commitMsg);