libgit2 / objective-git

Objective-C bindings to libgit2
MIT License
1.16k stars 280 forks source link

[Help] Commit a file in a subdirectory #694

Closed arguiot closed 5 years ago

arguiot commented 5 years ago

Hello, I have a repository containing mutliple subdirectories and would like to add a modified file inside those subdirectories:

For example, let's say my repository's path is / and that my modified file's path is /path/to/file.md:

My Swift code (Objective Git is imported using a bridging header, and works perfectly):

let r = repository // the GTRepository instance
let branch = try r.currentBranch()
let last = try branch.targetCommit()

let builder = try GTTreeBuilder(tree: last.tree, repository: r)

let subbuilder = try GTTreeBuilder(tree: nil, repository: r)
let name = "file.md"
try subbuilder.addEntry(with: data, fileName: name, fileMode: .blob) // The data is given in this example
let subtree = try subbuilder.writeTree()
subbuilder.clear()
try builder.addEntry(with: subtree.oid, fileName: "path/to/", fileMode: .tree)

But when I run this code, I'm getting an error saying that the tree can't be added back to the builder instance.

How am I supposed to add this file to the builder?

arguiot commented 5 years ago

Actually, I found a workaround:

let index = try r.index()
try index.addFile("/path/to/file.md")
try index.write()
let tree = try index.writeTree()

_ = try r.createCommit(with: tree, message: commitText, author: signature, committer: signature, parents: [last], updatingReferenceNamed: name)
tiennou commented 5 years ago

(Just to clarify, we generally prefer to use StackOverflow for support questions).

As to the issue you're having, it's caused by the treebuilder API being "not helpful": it will not automatically create trees from pathnames. So those filename arguments are really the name of the file segment of the object you're adding for the tree you're building. Hence, you need to : 1) build a tree with the data, named "file.md" 2) build a tree, with the oid of $1, named "to" 3) build a tree, with the oid of $2, named "path" 4) write the built tree