我目前正在努力将文件暂存并提交到内存中的git存储库(即无需将文件写入磁盘,添加并提交)
这是我的代码的缩短版本;它几乎有效
package main
import (
"fmt"
"gopkg.in/libgit2/git2go.v25"
"time"
)
func main() {
sig := &git.Signature{
Name: "Some Person",
Email: "somebody@something.org",
When: time.Now(),
}
repo, err := git.OpenRepository("./repo")
check(err)
defer repo.Free()
content := []byte("hello world")
index, err := repo.Index()
check(err)
oid, err := repo.CreateBlobFromBuffer(content)
check(err)
ie := git.IndexEntry{
Mode: git.FilemodeBlob,
Id: oid,
Path: "documents/document_9.md",
}
err = index.Add(&ie)
check(err)
treeId, err := index.WriteTree()
check(err)
tree, err := repo.LookupTree(treeId)
check(err)
index.Write()
currentBranch, err := repo.Head()
check(err)
currentTip, err := repo.LookupCommit(currentBranch.Target())
check(err)
commitId, err := repo.CreateCommit("HEAD", sig, sig, "A new commit", tree, currentTip)
check(err)
fmt.Println(commitId)
}
func check(err error) {
if err != nil {
panic(err)
}
}
然而,当我运行它并查看./repo
时,某些事情并不完全正确。从git status
可以看到,新的document_9.md
文件被标记为已删除(即git知道它但它不存在)
❯ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: documents/document_9.md
查看日志,它确认提交确实有效:
❯ git log --patch
commit a609b43e6a3f7da7d0589971ab0f64f3f432e76c
Author: Some Person <somebody@something.org>
Date: Thu Mar 23 19:43:56 2017 +0000
a new commit
diff --git a/documents/document_9.md b/documents/document_9.md
new file mode 100644
index 0000000..95d09f2
--- /dev/null
+++ b/documents/document_9.md
@@ -0,0 +1 @@
+hello world
\ No newline at end of file
commit 668762279b51483c05dbdedcf3c599a1b41c203b
Author: Original Committer <someguy@something.com>
Date: Thu Mar 23 19:42:52 2017 +0000
First commit
diff --git a/documents/docment_1.md b/documents/docment_1.md
new file mode 100644
index 0000000..2965834
--- /dev/null
+++ b/documents/docment_1.md
@@ -0,0 +1 @@
+# Hello World
我相信我错过了一步。不知何故,我需要确保我的提交已经同步&#39;与文件系统。我思考(根据文档),这是由index.Write()
和index.WriteTree()
实现的,但我无法让它发挥作用。
非常感谢任何朝着正确方向的推动。
答案 0 :(得分:1)
如果您希望工作目录与新HEAD提交的状态相匹配,那么您需要检查它(例如,使用等效的git_checkout_head
)。
git_index_write_tree
将树对象写入对象数据库,git_index_write
将索引的内存中表示写入磁盘。都不会影响工作目录。