Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sha of current git commit from R

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.

like image 973
Jindra Lacko Avatar asked Sep 23 '17 07:09

Jindra Lacko


People also ask

How do I see current commit hash?

# open the git config editor $ git config --global --edit # in the alias section, add ... [alias] lastcommit = rev-parse HEAD ... From here on, use git lastcommit to show the last commit's hash.

How does git generate Sha?

Git relies on the collision-resistance of SHA-1. (In practice, if you encounter such a collision, which I believe has never occurred outside of intentional attempts to create collisions), you can just add a space to the end of the commit message, which will generate a new hash.

Is SHA same as commit ID?

The SHA1 of the commit is the hash of all the information. And because this hash is unique to its content, a commit can't change. If you change any data about the commit, it will have a new SHA1. Even if the files don't change, the created date will.


2 Answers

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)
like image 62
John Zwinck Avatar answered Sep 30 '22 12:09

John Zwinck


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: [email protected]
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.

like image 39
Spacedman Avatar answered Sep 30 '22 14:09

Spacedman