Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodegit (libgit2 for Node.js): How to push and pull?

Tags:

git

node.js

I am trying to push or pull with nodegit.

The package is very popular and everything works but I can't seem to find these basic methods. What am I missing?

Any other packages?

like image 564
Guy Avatar asked Feb 15 '23 05:02

Guy


2 Answers

Try this for fetch and pull:

/**
 * Fetch from remote
 * fileName: pull.js
 *
 * @param {string} repositoryPath - Path to local git repository
 * @param {string} remoteName - Remote name
 * @param {string} branch - Branch to fetch
 */

var Git = require('nodegit');
var open = Git.Repository.open;   

module.exports = function (repositoryPath, remoteName, branch, cb) {
    var repository;
    var remoteBranch = remoteName + '/' + branch;
    open(repositoryPath)
        .then(function (_repository) {
            repository = _repository;
            return repository.fetch(remoteName);
        }, cb)
        .then(function () {
            return repository.mergeBranches(branch, remoteBranch);
        }, cb)
        .then(function (oid) {
            cb(null, oid);
        }, cb);
};

And then you can use of this way:

var pull = require('./pull.js');
var remoteRef = 'origin';

pull(repositoryPath, remoteRef, ourBranch, function(errFetch, oid) {
    if (errFetch) {
        return errFetch;
    }
    console.log(oid);
});

And Try this for push:

/**
 * Pushes to a remote
 *
 * @param {string} repositoryPath - Path to local git repository
 * @param {string} remoteName - Remote name
 * @param {string} branch - Branch to push
 * @param {doneCallback} cb
 */

var Git = require('nodegit');
var open = Git.Repository.open;

module.exports = function (repositoryPath, remoteName, branch, cb) {

    var repository, remoteResult;

    open(repositoryPath)
        .then(function (_repository) {
            repository = _repository;
            return repository.getRemote(remoteName);
        }, cb)
        .then(function (_remoteResult) {
            remoteResult = _remoteResult;
            return repository.getBranch(branch);
        }, cb)
        .then(function (ref) {
            return remoteResult.push([ref.toString()], new Git.PushOptions());
        }, cb)
        .then(function (number) {
            cb(null, number);
        }, cb);
};
like image 77
Leandro William Avatar answered Feb 17 '23 02:02

Leandro William


Examples available on the github site.

For fetch: https://github.com/nodegit/nodegit/blob/master/examples/fetch.js

For pull: https://github.com/nodegit/nodegit/issues/341:

repo.fetchAll({
  credentials: function(url, userName) {
    return NodeGit.Cred.sshKeyFromAgent(userName);
  }
}).then(function() {
  repo.mergeBranches("master", "origin/master");
});
like image 44
Bruce MacKenzie Avatar answered Feb 17 '23 02:02

Bruce MacKenzie