3

I've been able to write a file to a branch in a bare repository using the below code, but it only works for files in the root. I haven't been able to find a good example in the documentation of how to build a tree for a subfolder and use that as a commit.

async function writeFile(filename, buffer) {
  const signature = NodeGit.Signature.now('Jamie', 'jamie@diffblue.com');
  const repo = await NodeGit.Repository.openBare('java-demo.git');
  const commit = await repo.getBranchCommit('master');
  const rootTree = await commit.getTree();
  const builder = await NodeGit.Treebuilder.create(repo, rootTree);
  const oid = await NodeGit.Blob.createFromBuffer(repo, buffer, buffer.length);
  await builder.insert(filename, oid, NodeGit.TreeEntry.FILEMODE.BLOB);
  const finalOid = await builder.write();
  await repo.createCommit('refs/heads/master', signature, signature, 'Commit message', finalOid, [commit]);
}

const buffer = new Buffer('Hello\n', 'utf-8');
writeFile('test.txt', buffer).then(() => console.log('Done'));

What modifications would be needed to post in (for example) src/test.txt, instead of test.txt?

rjmunro
  • 27,203
  • 20
  • 110
  • 132
  • It seems that this issue is not very clear and no example exists in the nodegit repo. Did you find an answer or solution to this issue? – Astuanax May 30 '20 at 15:39

1 Answers1

2

The typical workflow for writing trees goes through the index. For example, git_index_add_frombuffer followed by git_index_write_tree. Even if you don't want to write to the repository's index on disk, you can still use the index interface by creating an in-memory index.

In a bare repository without an index, you can use git_index_new followed by git_index_read_tree to get an index initialized to the contents of your tree. Then write the tree out to the repository with git_index_write_tree_to.

I'm less familiar with the treebuilder interface, but it looks like you would have to create new subtrees recursively. For example, get or create the src subtree and insert the test.txt blob into it. Then get or create the root tree and insert the src subtree into it.

Jason Haslam
  • 2,617
  • 13
  • 19
  • Nodegit doesn't seem to have an equivalent to `git_index_add_frombuffer`, which means I'll have to try the creating subtrees recursively route for now... – rjmunro Nov 21 '18 at 10:13