javascript - Nodegit:如何修改文件并推送更改?

标签 javascript node.js git nodegit

四处寻找示例,但找不到。文档没有解释,我想不通。

如何修改文件(例如 README.md),为修改后的文件创建一个提交,然后将提交推送到服务器?

Nodegit:http://www.nodegit.org/

Nodegit 文档:http://www.nodegit.org/nodegit

最佳答案

有一个如何在他们的 repo 上创建/添加和提交的示例,可以帮助您修改文件。

https://github.com/nodegit/nodegit/blob/master/examples/add-and-commit.js

关于提交和推送,这是我的代码的外观片段,希望对您有所帮助。我花了很多时间才弄清楚这一点,感谢 Gitter 上的人,我终于找到答案了。

代码如下:

var path = require('path');

var nodegit = require('nodegit'),
    repoFolder = path.resolve(__dirname, 'repos/test/.git'),
    fileToStage = 'README.md';

var repo, index, oid, remote;

nodegit.Repository.open(repoFolder)
  .then(function(repoResult) {
    repo = repoResult;
    return repoResult.openIndex();
  })
  .then(function(indexResult) {
    index  = indexResult;

    // this file is in the root of the directory and doesn't need a full path
    index.addByPath(fileToStage);

    // this will write files to the index
    index.write();

    return index.writeTree();
  })
  .then(function(oidResult) {
    oid = oidResult;

    return nodegit.Reference.nameToId(repo, 'HEAD');
  })
  .then(function(head) {
    return repo.getCommit(head);
  })
  .then(function(parent) {
    author = nodegit.Signature.now('Author Name', 'author@email.com');
    committer = nodegit.Signature.now('Commiter Name', 'commiter@email.com');

    return repo.createCommit('HEAD', author, committer, 'Added the Readme file for theme builder', oid, [parent]);
  })
  .then(function(commitId) {
    return console.log('New Commit: ', commitId);
  })

  /// PUSH
  .then(function() {
    return repo.getRemote('origin');
  })
  .then(function(remoteResult) {
    console.log('remote Loaded');
    remote = remoteResult;
    remote.setCallbacks({
      credentials: function(url, userName) {
        return nodegit.Cred.sshKeyFromAgent(userName);
      }
    });
    console.log('remote Configured');

    return remote.connect(nodegit.Enums.DIRECTION.PUSH);
  })
  .then(function() {
    console.log('remote Connected?', remote.connected())

    return remote.push(
      ['refs/heads/master:refs/heads/master'],
      null,
      repo.defaultSignature(),
      'Push to master'
    )
  })
  .then(function() {
    console.log('remote Pushed!')
  })
  .catch(function(reason) {
    console.log(reason);
  })

希望这会有所帮助。

关于javascript - Nodegit:如何修改文件并推送更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870374/

相关文章:

javascript - 如何从外部更改vue应用程序的属性

node.js - 将子进程的输出保存在 NodeJS 父进程的变量中

git - 如何将 Altium 与 Git 一起使用?

node.js - 如何在 Angular 2 和 Node JS 中更新 ng2-chartjs2 图表中的数据

javascript - 在 express.js 中使用一组中间件

Git 错误 : previous rebase directory . git/rebase-apply 仍然存在但给出了 mbox

git - 如何在 openshift origin 中运行 docker 镜像而不通过 Web 控制台构建它

javascript - 无效标记重复属性

javascript - collection.fetch() 的选项

javascript - 搜索短语,循环执行不正确