Search code examples
rgitrstudioknitr

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


Solution

  • Doing this only for presenting a soup-to-nuts example. It was @Wander Nauta's idea (from comments on the question).

    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