10

Is there a way to get SHA of current GIT commit from R? I need to access it via a function call (not as a hard string).

I have adapted GIT as version control system for analysis, and want to print the SHA on footnote of my intermediate reports (my working drafts, in pdf format, get a life of their own and it is not immediately obvious by looking at them at what moment they were generated; this creates a reproducibility issue).

For reference: I am using R 3.4.1 via R Studio and creating reports via r markdown.

Imran Ali
  • 2,223
  • 2
  • 28
  • 41
Jindra Lacko
  • 7,814
  • 3
  • 22
  • 44

2 Answers2

12

You'll need to invoke the git rev-parse command as explained here: How to retrieve the hash for the current commit in Git?

You can do it using system():

https://stat.ethz.ch/R-manual/R-devel/library/base/html/system.html

Putting it together:

system("git rev-parse HEAD", intern=TRUE)
Spacedman
  • 92,590
  • 12
  • 140
  • 224
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
9

Install git2r package and then:

> library(git2r)
> r = revparse_single(path,"HEAD")
> sha(r)
[1] "f5bb1f115e9db0c732840298465488e8dfea5032"

It also gives you some other info about the commit too, in other members of the returned object:

> r$author
name:  Barry Rowlingson
email: b.rowlingson@lancs.ac.uk
when:  2022-01-12 18:37:14 GMT

These are documented in help(commit), but only sha seems to have an accessor function for it.

Spacedman
  • 92,590
  • 12
  • 140
  • 224