Узел: Как изменить файл и отправить изменения?

Посмотрел вокруг пример, но не смог его найти. Документация не объяснена и я не смог разобраться.

Как изменить файл (например, README.md), создать коммит для измененного файла и затем отправить коммит на сервер?

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

Документация по Nodegit: http://www.nodegit.org/nodegit

2 ответа

Решение

Существует пример того, как создавать / добавлять и фиксировать их репо, которые могут помочь вам с изменением файла.

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

Надеюсь это поможет.

Решение Рафаэля работает наверняка, хотя я могу добавить, что нет необходимости выполнять .connect в сервер. Вот минимальный подход к продвижению репо:

  • Нажав на мастер, используя только аутентификацию по имени пользователя и паролю:

            //Previous calls
    
            }).then(function() {
                return repo.getRemote("origin"); //Get origin remote
            }).then(function(remote) {
                return remote.push(["refs/heads/master:refs/heads/master"], {
                    callbacks: {
                        credentials: function(url, userName) {
                            console.log("Requesting creds");
    
                            return NodeGit.Cred.userpassPlaintextNew("[USERNAME]", "[PASSWORD]");
                        }
                    }
                });
            }).then(function(err) {
                console.log("Push error number:");
                console.log(err);
            }).catch(function(err) {
                console.log(err);
            }).done(function(commitId) {
                console.log("All done");
            })
    
  • Нажав на myBranch через SSH аутентификацию:

            //Previous calls
    
            }).then(function() {
                return repo.getRemote("origin"); //Get origin remote
            }).then(function(remote) {
                return remote.push(["refs/heads/myBranch:refs/heads/myBranch"], {
                    callbacks: {
                        credentials: function(url, userName) {
                            console.log("Requesting creds");
                            return NodeGit.Cred.sshKeyFromAgent(userName);
                        }
                    }
                });
            }).then(function(err) {
                console.log("Push error number:");
                console.log(err);
            }).catch(function(err) {
                console.log(err);
            }).done(function(commitId) {
                console.log("All done");
            })
    
Другие вопросы по тегам