使用GIT2r签出提交时出现问题

时间:2018-10-02 15:42:01

标签: r git

据我从git2r文档中得知,只有两种方法可以检索上一次提交:签出和重置。

我遇到的问题是,在两种情况下,我似乎都丢失了所有较新的提交。也许我不明白这里发生了什么?是那样工作吗?

我只在本地使用它,所以没有从任何地方推动或拉动,只是本地提交。

这些是我正在使用的命令:

# to create a new commit
repo <- repository(path = "/blah/blah/blah")
add(repo,"*")
commit(repo,"my new nice commit")

# to retrieve a previous commit:
checkout(commits(repo)[[2]]) # if only a single previous commit exists it will be number 2
OR
reset(commits(repo)[[2]])
再次

都会导致丢失较新的提交。有人知道发生了什么吗?

非常感谢您!

1 个答案:

答案 0 :(得分:1)

有两种方法可以解决此问题。首先,我将演示如何创建示例存储库,以便您可以准确地复制它:

library(git2r)
path <- "SOanswer"
dir.create(path)
repo <- init(path)
writeLines("Commit1", con = file.path(path, "commit1.txt"))
add(repo, "commit1.txt")
commit(repo, "First commit message")
repository_head(repo)
commits(repo)
writeLines("Commit2", con = file.path(path, "commit2.txt"))
add(repo, "commit2.txt")
commit(repo, "Second commit message")

现在,您的问题是,如果您运行checkout(commits(repo)[[2]]),将丢失提交2,并且该提交将不再显示在commits()中。但是,您只可以做git checkout master的等效项(有关纯git上下文中类似问题的讨论,请参见this question

list.files(path)
# [1] "commit1.txt" "commit2.txt"
checkout(commits(repo)[[2]])
list.files(path)
# [1] "commit1.txt"
checkout(repo, branch = "master")
list.files(path)
# [1] "commit1.txt" "commit2.txt"

这将带您进入master分支的HEAD。但是,假设您要进行特定的提交。您可以使用提交SHA来做到这一点。这是一个示例:

writeLines("Commit3", con = file.path(path, "commit3.txt"))
add(repo, "commit3.txt")
commit(repo, "Third commit message")
completed_commits <- commits(repo) # Store the commits so we know the SHAs
list.files(path)
# [1] "commit1.txt" "commit2.txt" "commit3.txt"
checkout(completed_commits[[3]])
list.files(path)
# [1] "commit1.txt"
checkout(completed_commits[[2]])
list.files(path)
# [1] "commit1.txt" "commit2.txt"
checkout(completed_commits[[1]])
list.files(path)
# [1] "commit1.txt" "commit2.txt" "commit3.txt"