Nodegit: connect and push

Created on 17 May 2016  路  5Comments  路  Source: nodegit/nodegit

I need to modify a file and push. Here is my code.
But it can't push, because it continually print "url" and "username". Please help me,thanks.

// 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,{
      credentials: function(url, userName) {
        console.log(url);
        console.log(userName);
        return nodegit.Cred.sshKeyFromAgent(userName);
      }
  });
}).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);
})

Most helpful comment

If you're using ssh agent on OSX you have to add your ssh key to your keychain. You can do that with:

ssh-add -K /path/of/private/key

Otherwise you can use NodeGit.Cred.sshKeyNew passing in both the private and public keys (both are required).

All 5 comments

Same issue. My config:

      const dir = path.resolve(this.basePath, config.dir);
      const pkg = require(this.basePath + '/package.json');

      let index, repository;

      this.log(`Initializing repo at ${dir}`);
      git.Repository.init(dir, 0)
        .then((repo) => {
          repository = repo;
          this.log(`refreshing index`);
          return repo.refreshIndex();
        })
        .then((idx) => {
          index = idx;
          this.log(`adding files`);
          return index.addAll();
        })
        .then(() => {
          this.log(`writing tree`);
          return index.writeTree();
        })
        .then((oid) => {
          this.log(`committing`);
          const author = git.Signature.create(pkg.author.name, pkg.author.email, Math.round(Date.now() / 1000), 60);
          return repository.createCommit("HEAD", author, author, "message", oid, []);
        })
        .then(() => {
          this.log(`adding remote`);
          return git.Remote.create(repository, 'origin', config.repo);
        })
        .then((remote) => {
          this.log(`pushing`);
          return remote.push([`refs/heads/master:refs/heads/${config.branch}`], {
            callbacks: {
              certificateCheck: () => 1,
              credentials: function(url, userName) {
                console.log(`getting creds for url:${url} username:${userName}`);
                return git.Cred.sshKeyFromAgent(userName);
              },
              transferProgress: (progress) => {
                this.log('progress: ', progress)
              }
            }
          })
        })
        .catch((e) => {
          console.log(e);
        })
        .done(() => {
          done();
        })

Output:

[19:42:35] Starting 'doc:deploy'...
[19:42:35] Initializing repo at /Users/zak/ubiquits/core/dist-docs
[19:42:35] refreshing index
[19:42:35] adding files
[19:42:35] writing tree
[19:42:35] committing
[19:42:35] adding remote
[19:42:35] pushing
getting creds for url:[email protected]:ubiquits/ubiquits.github.io.git username:git
getting creds for url:[email protected]:ubiquits/ubiquits.github.io.git username:git
getting creds for url:[email protected]:ubiquits/ubiquits.github.io.git username:git
getting creds for url:[email protected]:ubiquits/ubiquits.github.io.git username:git
getting creds for url:[email protected]:ubiquits/ubiquits.github.io.git username:git
[...etc]
  • MacOS 10.11.5
  • "nodegit": "^0.13.0",
  • node v6.2.0

Update - this issue may be isolated to mac - the same code works fine on travis ci. @feifeipan are you using a mac?

If you're using ssh agent on OSX you have to add your ssh key to your keychain. You can do that with:

ssh-add -K /path/of/private/key

Otherwise you can use NodeGit.Cred.sshKeyNew passing in both the private and public keys (both are required).

Here is a simple example in which I can use agent, but no success using sshKeyNew.

var nodegit = require('nodegit');
var fse = require('fs-extra');
var path = require('path');
var local = path.join.bind(path, __dirname);

var sshPublicKeyPath = '/Users/ajonp/.ssh/id_rsa.pub';
var sshPrivateKeyPath = '/Users/ajonp/.ssh/id_rsa';

var clonePath = local('../repos/clone');
var debug = 0;

console.log('clonepath',clonePath)

fse.remove(clonePath).then(async function() {
  try {
    const repo = await nodegit.Clone(
      '[email protected]:AJONPLLC/lesson-8-hugo.git',
      clonePath,
      {
        fetchOpts: {
          callbacks: {
            certificateCheck: () => {
              // github will fail cert check on some OSX machines
              // this overrides that check
              return 1;
            },
            credentials: (url, userName) => {
                console.log(sshPublicKeyPath)
                console.log(sshPrivateKeyPath)
                // avoid infinite loop when authentication agent is not loaded
                if (debug++ > 10){
                    console.log('Failed too often, bailing.')
                    throw "Authentication agent not loaded.";
                }
              return nodegit.Cred.sshKeyNew(
                userName,
                sshPublicKeyPath,
                sshPrivateKeyPath,
                ''
              );
            // return nodegit.Cred.sshKeyFromAgent(userName);
            }
          }
        }
      }
    );
  } catch (err) {
    console.log(err);
  }
});

SSH works fine testing direct to github.

{ [Error: Failed to authenticate SSH session: Invalid public key data] errno: -1, errorFunction: 'Remote.push' }

Was this page helpful?
0 / 5 - 0 ratings