节点it bitbucket提交工作不正常nodejs

drnojrws  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(146)

我正在尝试使用nodegit npm包将更改推送到bitbucket repo。
下面是代码

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);
          }
        });
    });
}

它正在进行提交和推送(也在bitbucket网站上检查),但没有更新文件内容。在VS代码上,同一文件正在过渡和更改中。
有什么问题?

t2a7ltrp

t2a7ltrp1#

我终于得到了解决方案,它正在工作

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);

相关问题