Show Git version in R Code

I am using Git as a version control (currently the centralised workflow, but I would like to move to feature branch or gitflow workflow). I use RStudio/Knitr to compile PDF documents and would like to know how I can automatically include the current Git version in the PDF – if that works? That way, when somebody comes back to me with a document I have given them, I know how to return to that point in the code. Any suggestions will be much appreciated, thanks – Marie.

Edit: Keywords is what I had in mind, although according to this post (gelato.unsw.edu.au/archives/git/0610/28891.html) not recommended. Are there any recommendations on helper scripts? – user1420372 just now

  • R: Error in namespaceExport(ns, exports) : undefined exports:
  • Rstudio greyed out Git commands and (No branch)
  • How to specify lib directory when installing development version R Packages from github repository
  • .gitignored files still shown in RStudio
  • RStudio and Git Yosemite
  • RStudio gives “Incorrect function” when setting git as Version control
  • Changing Git protocol for RStudio project already under version control in Windows
  • Download, Revise, Upload Github Gists with R
  • 2 Solutions collect form web for “Show Git version in R Code”

    Doing this only for presenting a soup-to-nuts example. It was @Wanter Nuata’s idea.

    Here’s a tiny knitr doc:

    ---
    output: pdf_document
    ---
    
    ```{r}
    print(system("git rev-parse --short HEAD", intern = TRUE))
    ```
    

    that I have in a freshly created local git repo.

    When I knit to PDF I get this:

    enter image description here

    so you should be able to use this for watermarking the git commit it was generated from.

    Alternately, if you’re good with adding another package dependency to your projects, you can use the git2r package:

    ---
    output: pdf_document
    ---
    
    ```{r}
    library(git2r)
    
    repo <- repository(".")
    print(head(repo))
    ```
    

    Which gives:

    enter image description here

    The suggestion to use the git2r package is a really good one. With a few more functions, you can isolate the actual SHA. You can also repurpose, e.g., the Author field to get the SHA in the document header, if that is of interest.

    Here’s the R Markdown document:

    ---
    title: "Show Git version in R Code"
    output: html_document
    date: "`r format(Sys.time(), '%d %B, %Y')`"
    author: "SHA: `r git2r::branch_target(git2r::head(git2r::repository(getwd())))`"
    ---
    
    You could also put the SHA elsewhere, like in a concluding chunk along with session info.
    
    ```{r collapse = TRUE}
    git2r::branch_target(git2r::head(git2r::repository(getwd())))
    ## ADD devtools::session_info() or sessionInfo() ??
    ```
    

    Which gives

    enter image description here

    Git Baby is a git and github fan, let's start git clone.