# Identity guard for R projects. # Stops with an error if the git author or GitHub account in use is not the # one this project expects. Source it at the top of any script that commits, # pushes, publishes or deploys. # # nolint start: commented_code_linter. Usage example. # source("R/identity-check.R") # assert_identity( # expected_email_pattern = "noreply\\.github\\.com$", # blocked_pattern = "@example-employer\\.com$", # expected_github_login = "my-company-bot" # optional # ) # nolint end git_value <- function(key) { out <- suppressWarnings( system2("git", c("config", "--get", key), stdout = TRUE, stderr = FALSE) ) if (length(out) == 0) NA_character_ else out[[1]] } github_login <- function() { if (!requireNamespace("gh", quietly = TRUE)) { return(NA_character_) } # gh_whoami() returns NULL (with a message) when no token is found. who <- tryCatch(suppressMessages(gh::gh_whoami()), error = function(e) NULL) if (is.null(who$login)) NA_character_ else who$login } assert_identity <- function( expected_email_pattern, blocked_pattern = NULL, expected_github_login = NULL ) { email <- git_value("user.email") login <- if (is.null(expected_github_login)) NA_character_ else github_login() checked <- c(email, login) checked <- checked[!is.na(checked)] problems <- character() if (is.na(email)) { problems <- c(problems, "git user.email is not set") } else if (!grepl(expected_email_pattern, email)) { problems <- c( problems, sprintf( "git user.email '%s' does not match '%s'", email, expected_email_pattern ) ) } if ( !is.null(blocked_pattern) && any(grepl(blocked_pattern, checked, ignore.case = TRUE)) ) { problems <- c(problems, "an active identity matches the blocked pattern") } if ( !is.null(expected_github_login) && !identical(login, expected_github_login) ) { problems <- c( problems, sprintf( "GitHub login is '%s', expected '%s'", login, expected_github_login ) ) } if (length(problems) > 0) { stop( "Identity check failed:\n- ", paste(problems, collapse = "\n- "), call. = FALSE ) } message( "āœ“ git: ", email, if (!is.na(login)) paste0("\nāœ“ GitHub: ", login) else "" ) invisible(TRUE) }