R/utils-git.R

Defines functions util_git_commit_id util_git_check_uncommitted

Documented in util_git_check_uncommitted util_git_commit_id

#' Check if git repo has uncommitted changes
#'
#' @param path the path to the directory to check.
#' @param dir_ignore name of subdirectory to skip over for uncommitted files.
#' should generally be the output directory for rmarkdown rendered files
#' (e.g., "docs/" for bookdown projects.)
#'
#' @return Invisible \code{NULL} if \code{path} is not a Git repository or has no
#'   relevant uncommitted changes. Throws an error otherwise.
#'
#' @export
#' @author Saannidhya Rawat
util_git_check_uncommitted <- function(path = ".",
                                       dir_ignore = "docs/") {

  if (git2r::in_repository(path = path)) {

    status <- gert::git_status()

    uncommitted_files <-
      status %>%
      # filter out untracked new files
      dplyr::filter(status != "new") %>%
      # filter out ignored directories
      dplyr::filter(grepl(dir_ignore, file) == FALSE) %>%
      dplyr::pull(file)

    if (length(uncommitted_files) > 0) {
      usethis::ui_stop("Uncommited changes. Please commit to git before continuing.
                       Use `git2r::status(untracked = TRUE)` to see uncommitted files.")
    }

  }

  invisible(NULL)

}

#' Get git commit ID
#'
#' @param path the path to the directory
#'
#' @return A length-one character vector containing the current Git SHA, or
#'   \code{NULL} if \code{path} is not a Git repository.
#'
#' @export
#' @author Saannidhya Rawat
util_git_commit_id <- function(path = "."){

  if(git2r::in_repository(path = path)){
    paste("Git SHA:", git2r::branch_target(git2r::repository_head(repo = path)))
  }

}

Try the Rbearcat package in your browser

Any scripts or data that you put into this service are public.

Rbearcat documentation built on March 21, 2026, 5:07 p.m.