|
| 1 | +#' @noRd |
| 2 | +extract_urls_from_file <- function(file) { |
| 3 | + content <- readLines(file, warn = FALSE) |
| 4 | + url_pattern <- "(http|https)://[a-zA-Z0-9./?=_-]*" |
| 5 | + urls <- unique(unlist(regmatches(content, gregexpr(url_pattern, content)))) |
| 6 | + names(urls) <- rep(file, length(urls)) |
| 7 | + return(urls) |
| 8 | +} |
| 9 | + |
| 10 | +#' @noRd |
| 11 | +check_url <- function(url) { |
| 12 | + response <- try(httr::GET(url), silent = TRUE) |
| 13 | + if (inherits(response, "try-error")) { |
| 14 | + res <- FALSE |
| 15 | + } |
| 16 | + |
| 17 | + res <- httr::status_code(response) == 200 |
| 18 | + res <- stats::setNames(res, url) |
| 19 | + |
| 20 | + return(res) |
| 21 | +} |
| 22 | + |
| 23 | +#' Check for the validity of the URLs in the R folder |
| 24 | +#' |
| 25 | +#' @param exclude a character vector of urls to exclude |
| 26 | +#' |
| 27 | +#' @return a message if some URLs are invalid |
| 28 | +#' @export |
| 29 | +check_url_validity <- function(exclude = NA_character_) { |
| 30 | + if (!curl::has_internet()) { |
| 31 | + cli::cli_alert_info("No internet connection.") |
| 32 | + return(invisible(FALSE)) |
| 33 | + } |
| 34 | + |
| 35 | + if (!dir.exists("R")) { |
| 36 | + cli::cli_alert_info("No R folder found.") |
| 37 | + return(invisible(FALSE)) |
| 38 | + } |
| 39 | + |
| 40 | + urls <- purrr::map( |
| 41 | + files, |
| 42 | + ~ extract_urls_from_file(file = .x) |
| 43 | + ) |> |
| 44 | + unlist() |> |
| 45 | + purrr::discard( |
| 46 | + ~ .x %in% exclude |
| 47 | + ) |> |
| 48 | + purrr::map( |
| 49 | + check_url |
| 50 | + ) |
| 51 | + |
| 52 | + invalid_urls <- urls |> |
| 53 | + purrr::keep( |
| 54 | + ~ .x == FALSE |
| 55 | + ) |
| 56 | + |
| 57 | + if (length(invalid_urls) > 0) { |
| 58 | + cli::cli_alert_info("Some URLs are invalid.") |
| 59 | + purrr::walk( |
| 60 | + invalid_urls, |
| 61 | + ~ cli::cli_alert_danger(sprintf("URL %s is invalid in file {.file %s}", names(.x), names(invalid_urls))) |
| 62 | + ) |
| 63 | + } else { |
| 64 | + cli::cli_alert_success("All URLs are valid.") |
| 65 | + } |
| 66 | +} |
0 commit comments