有几种方法可以解决这个问题。首先,我将演示如何创建示例存储库,这样您就可以准确地复制:
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"
这会把你带到总支的头上。但是,假设您想进行特定的提交。你可以用commit-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"