Sam Firke
Sam Firke

Reputation: 23014

How to add pre-commit git hooks to check that README.Rmd and index.Rmd have been knitted?

I have an R package with a pkgdown documentation site. I want to create a git hook so that if I try to commit and push changes to either README.Rmd or index.Rmd without first knitting them to create the corresponding .Md files, I'm warned. Right now I just forget.

The book R Packages says to use usethis::use_readme_rmd() to create the README, which will also create the git hook. But I already have a README.Rmd file.

How can I create a hook for an existing .Rmd file generally, whether it's README.Rmd or the index.Rmd from my pkgdown site? I'd like to use the usethis package but if it's simpler to do it outside of that package, I'm open to that.

Upvotes: 1

Views: 1376

Answers (1)

Eli Holmes
Eli Holmes

Reputation: 676

A different approach is to do this with Github Actions if that is where your pkgdown site is.

  1. Create the folder .github within your repo
  2. Within that create the folder workflows
  3. Within that create the file render-readme.yml
  4. Paste this code in that file
on:
  push:
    paths:
      - README.Rmd
      - Index.Rmd

name: Render README and Index

jobs:
  render:
    name: Render README and Index
    runs-on: macOS-latest
    steps:
      - uses: actions/checkout@v2
      - uses: r-lib/actions/setup-r@v1
      - uses: r-lib/actions/setup-pandoc@v1
      - name: Install packages
        run: Rscript -e 'install.packages(c("rmarkdown", "knitr"))'
      - name: Render README
        run: Rscript -e 'rmarkdown::render("README.Rmd", output_format = "md_document")'
      - name: Render Index
        run: Rscript -e 'rmarkdown::render("Index.Rmd", output_format = "md_document")'
      - name: Commit results
        run: |
          git commit README.md -m 'Re-build README.Rmd' || echo "No changes to commit"
          git commit Index.md -m 'Re-build Index.Rmd' || echo "No changes to commit"
          git push origin || echo "No changes to commit"
  1. Push this to GitHub and it should start working immediately. Note it takes a bit of time to process. Click on the Actions tab in your GitHub repo to see the progress.

See https://github.com/r-lib/actions for examples. Code above is adapted from that.

Note you might want to divide the action into 2 files. render-readme.yml and render-index.yml. That way if the Action fails, you'll know which file has the problem.

Upvotes: 0

Related Questions