2

As far as I can tell from the git2r documentation there are only two ways to retrieve a previous commit: checkout and reset.

The problem that I have is that in both cases, I seem to lose all newer commits. Maybe I don't understand what is happening here? Is it meant to work like that?

I am only using it locally, so no pushing or pulling from anywhere, just local commits.

These are the commands I am using:

# 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]])

again both result in losing the newer commits. Does anybody know what is happening.

Thank you very much beforehand!

duckmayr
  • 16,303
  • 3
  • 35
  • 53
Jesus Rp
  • 23
  • 2

1 Answers1

1

There are a couple of ways to solve this issue. First, I'll demonstrate the creation of an example repository so you can reproduce this exactly:

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")

Now your problem is if you run checkout(commits(repo)[[2]]), you would lose commit 2, and it would no longer show up in commits(). However, you can just do the equivalent of git checkout master (for a discussion of similar issues in the plain git context, see, for example, 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"

This would bring you to the HEAD of the master branch. However, suppose you wanted to go to a specific commit. You could do that with the commit SHA. Here's an example:

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"
duckmayr
  • 16,303
  • 3
  • 35
  • 53
  • That makes a lot more sense now. It it definitely confusing to work with git2r when coming from other options. Thanks so much! – Jesus Rp Oct 04 '18 at 13:10