diff --git a/DESCRIPTION b/DESCRIPTION index de12ccec..b178e04d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -16,7 +16,7 @@ URL: https://Require.predictiveecology.org, https://github.com/PredictiveEcology/Require Date: 2026-09-04 -Version: 2.1.1.9055 +Version: 2.1.1.9057 Authors@R: c( person(given = "Eliot J B", family = "McIntire", @@ -43,24 +43,14 @@ Imports: tools, utils Suggests: - cli, - covr, curl, - diffobj, - fpCompare, gitcreds, httr, parallel, - pkgcache, pkgload, - rematch2, rmarkdown, knitr, - rlang, - roxygen2, - rprojroot, testthat (>= 3.0.0), - waldo, withr Encoding: UTF-8 Language: en-CA diff --git a/NEWS.md b/NEWS.md index e9a6f654..1c8f473f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,6 +3,8 @@ ## Dependency changes * Require now needs R >= 4.3 (was 4.1), the oldest R version its checks run on (#220). +* Nine packages that nothing in Require's code or tests needs are no longer in Suggests (cli, covr, diffobj, fpCompare, pkgcache, rematch2, rlang, roxygen2, waldo), and `rprojroot` is gone too: `setupOff()` now looks for the `*.Rproj` folder with base R. +* Require's own downloads from GitHub that use the user's git credentials now go through `curl` instead of `httr`. `GETWauthThenNonAuth()` is unchanged and still returns an `httr` response, because the SpaDES packages read it with `httr`; `httr` stays in Suggests for it. ## Removed diff --git a/R/Require-helpers.R b/R/Require-helpers.R index ba6b052f..0841db5f 100644 --- a/R/Require-helpers.R +++ b/R/Require-helpers.R @@ -1298,7 +1298,7 @@ masterMainHEAD <- function(url, need) { token <- checkForToken() # token <- NULL # usesGitCreds <- requireNamespace("gitcreds", quietly = TRUE) && - # requireNamespace("httr", quietly = TRUE) + # requireNamespace("curl", quietly = TRUE) # if (usesGitCreds) { # token <- getGitCredsToken() # } @@ -1341,9 +1341,9 @@ masterMainHEAD <- function(url, need) { messageVerbose(e$message, verbose = verbose) }) } else { - a <- try(GETWauthThenNonAuth(URL, token, verbose = verbose), silent = TRUE) + a <- try(curlGETauth(URL, token, verbose = verbose), silent = TRUE) if (is(a, "try-error")) { - # as without a token: keep the error and try again; httr::content() of a + # as without a token: keep the error and try again; reading the content of a # try-error stopped with "is.response(x) is not TRUE" lastErr <- conditionMessage(attr(a, "condition")) if (tryNum > 1) @@ -1352,11 +1352,7 @@ masterMainHEAD <- function(url, need) { warning(a) next } - # a <- httr::GET(url, httr::add_headers(Authorization = token)) - # if (grepl("Bad credentials", a) || grepl("404", a$status_code)) - # a <- httr::GET(url, httr::add_headers()) - data <- httr::content(a, "raw") - writeBin(data, df) + writeBin(a$content, df) } if (file.exists(df)) break @@ -1378,12 +1374,10 @@ masterMainHEAD <- function(url, need) { outMasterMain <- try(download.file(urls[["TRUE"]][wh], destfile = destfile, quiet = TRUE), silent = TRUE) } else { outMasterMain <- try(silent = TRUE, { - a <- GETWauthThenNonAuth(urls[["TRUE"]][wh], token, verbose = verbose) - # a <- httr::GET(urls[["TRUE"]][wh], httr::add_headers(Authorization = token)) - if (grepl("404", httr::http_status(a)$message)) + a <- curlGETauth(urls[["TRUE"]][wh], token, verbose = verbose) + if (a$status_code == 404L) stop() - data <- httr::content(a, "raw") - writeBin(data, destfile) + writeBin(a$content, destfile) }) if (is.null(outMasterMain)) outMasterMain <- 0 } @@ -1560,6 +1554,30 @@ GETWauthThenNonAuth <- function(url, token, verbose = getOption("Require.verbose a } +## What Require itself downloads with: GETWauthThenNonAuth() through curl, which +## returns the curl_fetch_memory() list (status_code, content) instead of an httr +## response. GETWauthThenNonAuth() stays on httr for the SpaDES packages, which read +## its result with httr::content() and httr::stop_for_status(). +curlGETauth <- function(url, token, verbose = getOption("Require.verbose")) { + a <- curlGET(url, token) + badCreds <- grepl("Bad credentials", rawToChar(a$content[a$content != as.raw(0)])) + if (badCreds || a$status_code == 404L) { + if (badCreds) messageVerbose(red("Git credentials do not work for this url: ", url, + "\nAre they expired?"), verbose = verbose) + a <- curlGET(url) + } + a +} + +## One GET, in memory, with the token (if any) as the Authorization header. As before, +## an HTTP error status is returned, not raised; a connection failure is an error. +curlGET <- function(url, token = NULL) { + h <- curl::new_handle() + if (!is.null(token)) + curl::handle_setheaders(h, Authorization = token) + curl::curl_fetch_memory(url, h) +} + available.packagesWithCallingHandlers <- function(repo, type, verbose = getOption("Require.verbose")) { @@ -1731,7 +1749,7 @@ readLinesWithHandlers <- function(fff) { ) } - # if (grepl("404", httr::http_status(a)$message)) { + # if (a$status_code == 404L) { # offerGitHubSuggestions(account, repo) # stop("The following repository does not seem to exist: \n", # paste(pkgDTNotLocal$packageFullName[has404], collapse = "\n"), @@ -1792,7 +1810,7 @@ apiGithubDotCom <- "https://api.github.com" checkForToken <- function() { token <- NULL usesGitCreds <- requireNamespace("gitcreds", quietly = TRUE) && - requireNamespace("httr", quietly = TRUE) + requireNamespace("curl", quietly = TRUE) if (usesGitCreds) { token <- getGitCredsToken() } diff --git a/R/setup.R b/R/setup.R index 00ff8c83..45035061 100644 --- a/R/setup.R +++ b/R/setup.R @@ -287,6 +287,18 @@ setup <- function(newLibPaths, return(invisible()) } +# The closest directory, from `start` up to the file-system root, that holds a `*.Rproj` +# file (an RStudio project); NULL if there is none. +findRprojDir <- function(start = getwd()) { + d <- normalizePath(start, winslash = "/", mustWork = FALSE) + repeat { + if (length(list.files(d, pattern = "\\.Rproj$")) > 0) return(d) + parent <- dirname(d) + if (identical(parent, d)) return(NULL) + d <- parent + } +} + #' @rdname setup #' @inheritParams Require #' @export @@ -295,8 +307,7 @@ setupOff <- function(removePackages = FALSE, verbose = getOption("Require.verbos updateRprofile <- checkTRUERprofile(TRUE) if (!file.exists(updateRprofile)) { # not in current dir ## 1. Check project - # find_root() stops when the working directory is not in an RStudio project - possDirs <- c(tryCatch(rprojroot::find_root(rprojroot::is_rstudio_project), error = function(e) NULL), "~") + possDirs <- c(findRprojDir(), "~") for (possDir in possDirs) { possFile <- file.path(possDir, updateRprofile) if (file.exists(possFile)) { diff --git a/tests/testthat/test-04other_testthat.R b/tests/testthat/test-04other_testthat.R index 97183159..1bcff7b9 100644 --- a/tests/testthat/test-04other_testthat.R +++ b/tests/testthat/test-04other_testthat.R @@ -224,7 +224,6 @@ test_that("test 4", { pkgs <- c("fpCompare", "rlang", "cli", "crayon", "stringr", "lobstr") a <- unique(extractPkgName(unlist(unname(pkgDep(pkgs))))) cacheClearPackages(a, ask = FALSE) - library(waldo) setLibPaths(tempdir3()) try(remove.packages(a)) options(Require.installPackagesSys = 1L) diff --git a/tests/testthat/test-14coverage2_testthat.R b/tests/testthat/test-14coverage2_testthat.R index aab0ae78..10f187da 100644 --- a/tests/testthat/test-14coverage2_testthat.R +++ b/tests/testthat/test-14coverage2_testthat.R @@ -247,7 +247,7 @@ test_that("setup() deprecated emits a deprecation warning", { test_that("setupOff() with no .Rprofile just messages", { td <- tempdir2("setupOffNoRprofile") - # Create a minimal .Rproj so rprojroot::find_root doesn't error + # a project folder, so findRprojDir() finds td writeLines("Version: 1.0\n", file.path(td, "test.Rproj")) origDir <- setwd(td) on.exit(setwd(origDir), add = TRUE) diff --git a/tests/testthat/test-15bugfixes_testthat.R b/tests/testthat/test-15bugfixes_testthat.R index 61fdf808..f3502919 100644 --- a/tests/testthat/test-15bugfixes_testthat.R +++ b/tests/testthat/test-15bugfixes_testthat.R @@ -431,7 +431,7 @@ test_that("Require.downloadTimeout raises options(timeout) during GH download (i oldTimeout <- getOption("timeout") observed <- NULL # Force a token-less code path (the `download.file` branch) by ensuring - # checkForToken() returns NULL. Tokens go through httr::GET instead. + # checkForToken() returns NULL. Tokens go through curl instead. withr::with_options( list( Require.downloadTimeout = 1234L, diff --git a/tests/testthat/test-28coverage4_testthat.R b/tests/testthat/test-28coverage4_testthat.R index e0f67c1b..b32f49c3 100644 --- a/tests/testthat/test-28coverage4_testthat.R +++ b/tests/testthat/test-28coverage4_testthat.R @@ -434,21 +434,18 @@ test_that(".downloadFileMasterMainAuth with a GITHUB_PAT puts it in the url but expect_no_match(c(mess, names(out), unlist(out)), "ghp_SECRET") }) -## An httr response, as much of one as Require reads. +## A curl::curl_fetch_memory() response, as much of one as Require reads. fakeResponse <- function(url, body, status = 200L) { - structure(list(url = url, status_code = status, - headers = structure(list(`content-type` = "text/plain; charset=utf-8"), - class = c("insensitive", "list")), - content = charToRaw(body)), class = "response") + list(url = url, status_code = status, content = charToRaw(body)) } -test_that(".downloadFileMasterMainAuth with a token goes through GETWauthThenNonAuth", { - skip_if_not_installed("httr") +test_that(".downloadFileMasterMainAuth with a token goes through curlGETauth", { + skip_if_not_installed("curl") localNoGitHubAccess() asked <- character() local_mocked_bindings( getGitCredsToken = function() "token abc", - GETWauthThenNonAuth = function(url, token, ...) { + curlGETauth = function(url, token, ...) { asked <<- c(asked, url) expect_identical(token, "token abc") if (grepl("/main/|/dev/", url)) fakeResponse(url, "the file") else fakeResponse(url, "404: Not Found", 404L) @@ -482,7 +479,7 @@ test_that(".downloadFileMasterMainAuth with a token goes through GETWauthThenNon file.path(d, "f4")), "not vectorized") ## no connection: nothing written, no error - local_mocked_bindings(GETWauthThenNonAuth = function(...) stop("Could not resolve host: github.com"), + local_mocked_bindings(curlGETauth = function(...) stop("Could not resolve host: github.com"), .package = "Require") capture.output(type = "message", out <- Require:::.downloadFileMasterMainAuth("https://raw.githubusercontent.com/acct/repo/dev/DESCRIPTION", @@ -490,6 +487,60 @@ test_that(".downloadFileMasterMainAuth with a token goes through GETWauthThenNon expect_false(file.exists(file.path(d, "f5"))) }) +test_that("curlGETauth sends the token, and tries without it on bad credentials or a 404", { + skip_if_not_installed("curl") + calls <- list() # the headers each request was given + answers <- list() + local_mocked_bindings( + handle_setheaders = function(handle, ...) { + headers <<- list(...) + invisible(TRUE) + }, + curl_fetch_memory = function(url, handle = NULL) { + calls[[length(calls) + 1]] <<- headers + headers <<- list() # each request has its own handle + answers[[length(calls)]] + }, + .package = "curl") + headers <- list() + hasAuth <- function() vapply(calls, function(x) "Authorization" %in% names(x), logical(1)) + u <- "https://api.github.com/repos/acct/repo" + + answers <- list(fakeResponse(u, "ok")) + out <- Require:::curlGETauth(u, "token abc", verbose = -2) + expect_identical(rawToChar(out$content), "ok") + expect_identical(hasAuth(), TRUE) + expect_identical(calls[[1]][["Authorization"]], "token abc") + + ## no token: one plain request + calls <- list(); headers <- list() + out <- Require:::curlGETauth(u, NULL, verbose = -2) + expect_identical(hasAuth(), FALSE) + + ## a 404 with the token: again without + calls <- list() + answers <- list(fakeResponse(u, "Not Found", 404L), fakeResponse(u, "public")) + out <- Require:::curlGETauth(u, "token abc", verbose = -2) + expect_identical(hasAuth(), c(TRUE, FALSE)) + expect_identical(rawToChar(out$content), "public") + + ## an expired token: says so, and tries without + calls <- list() + answers <- list(fakeResponse(u, '{"message":"Bad credentials"}', 401L), fakeResponse(u, "public")) + expect_message(out <- Require:::curlGETauth(u, "token abc", verbose = 1), + "Git credentials do not work for this url") + expect_identical(hasAuth(), c(TRUE, FALSE)) + expect_identical(rawToChar(out$content), "public") +}) + +## An httr response, as much of one as Require reads. +fakeHttrResponse <- function(url, body, status = 200L) { + structure(list(url = url, status_code = status, + headers = structure(list(`content-type` = "text/plain; charset=utf-8"), + class = c("insensitive", "list")), + content = charToRaw(body)), class = "response") +} + test_that("GETWauthThenNonAuth sends the token, and tries without it on bad credentials or a 404", { skip_if_not_installed("httr") calls <- list() @@ -503,7 +554,7 @@ test_that("GETWauthThenNonAuth sends the token, and tries without it on bad cred hasAuth <- function() vapply(calls, function(x) "Authorization" %in% names(x$headers), logical(1)) u <- "https://api.github.com/repos/acct/repo" - answers <- list(fakeResponse(u, "ok")) + answers <- list(fakeHttrResponse(u, "ok")) out <- Require:::GETWauthThenNonAuth(u, "token abc", verbose = -2) expect_identical(rawToChar(out$content), "ok") expect_identical(hasAuth(), TRUE) @@ -516,14 +567,14 @@ test_that("GETWauthThenNonAuth sends the token, and tries without it on bad cred ## a 404 with the token: again without calls <- list() - answers <- list(fakeResponse(u, "Not Found", 404L), fakeResponse(u, "public")) + answers <- list(fakeHttrResponse(u, "Not Found", 404L), fakeHttrResponse(u, "public")) out <- Require:::GETWauthThenNonAuth(u, "token abc", verbose = -2) expect_identical(hasAuth(), c(TRUE, FALSE)) expect_identical(rawToChar(out$content), "public") ## an expired token: says so, and tries without calls <- list() - answers <- list(fakeResponse(u, '{"message":"Bad credentials"}', 401L), fakeResponse(u, "public")) + answers <- list(fakeHttrResponse(u, '{"message":"Bad credentials"}', 401L), fakeHttrResponse(u, "public")) expect_message(out <- Require:::GETWauthThenNonAuth(u, "token abc", verbose = 1), "Git credentials do not work for this url") expect_identical(hasAuth(), c(TRUE, FALSE)) @@ -539,6 +590,73 @@ fakeGitRefs <- function(branches) { '"url":"https://api.github.com/repos/acct/repo/git/commits/', branches, '"}}', collapse = ","), "]") } +test_that(".downloadFileMasterMainAuth with a token writes what curl fetched, and falls back on bad credentials, a 404 or no host", { + skip_if_not_installed("curl") + localNoGitHubAccess() + sent <- list() # url and whether it carried the token, per request + headers <- list() + answer <- function(url) fakeResponse(url, "the file") + local_mocked_bindings( + handle_setheaders = function(handle, ...) { + headers <<- list(...) + invisible(TRUE) + }, + curl_fetch_memory = function(url, handle = NULL) { + sent[[length(sent) + 1]] <<- list(url = url, auth = "Authorization" %in% names(headers)) + headers <<- list() + answer(url) + }, + .package = "curl") + local_mocked_bindings(getGitCredsToken = function() "token abc", + download.file = function(...) stop("download.file should not be used with a token"), + .package = "Require") + d <- withr::local_tempdir() + authSeq <- function() vapply(sent, `[[`, logical(1), "auth") + dev <- "https://raw.githubusercontent.com/acct/repo/dev/DESCRIPTION" + + ## a success writes the file, bytes as sent + Require:::.downloadFileMasterMainAuth(dev, file.path(d, "f1"), need = "master", verbose = -2) + expect_identical(authSeq(), TRUE) + expect_identical(readLines(file.path(d, "f1"), warn = FALSE), "the file") + + ## bad credentials: the request is repeated without the header, and that answer is written + sent <- list() + answer <- function(url) if (length(sent) == 1) fakeResponse(url, '{"message":"Bad credentials"}', 401L) else + fakeResponse(url, "public file") + Require:::.downloadFileMasterMainAuth(dev, file.path(d, "f2"), need = "master", verbose = -2) + expect_identical(authSeq(), c(TRUE, FALSE)) + expect_identical(readLines(file.path(d, "f2"), warn = FALSE), "public file") + + ## a 404 on master: retried without the token, then main is tried + sent <- list() + master <- "https://raw.githubusercontent.com/acct/repo/master/DESCRIPTION" + answer <- function(url) if (grepl("/master/", url)) fakeResponse(url, "Not Found", 404L) else + fakeResponse(url, "from main") + out <- Require:::.downloadFileMasterMainAuth(master, file.path(d, "f3"), need = "master", verbose = -2) + expect_identical(authSeq(), c(TRUE, FALSE, TRUE)) + expect_match(sent[[3]]$url, "/main/") + expect_identical(readLines(file.path(d, "f3"), warn = FALSE), "from main") + + ## a host that cannot be resolved: no file, an error to the caller (the second round finds offline mode on), and offline mode + sent <- list() + answer <- function(url) stop("Could not resolve host: raw.githubusercontent.com") + local_mocked_bindings(internetExists = function(...) FALSE, .package = "Require") + capture.output(type = "message", + out <- Require:::.downloadFileMasterMainAuth(dev, file.path(d, "f4"), need = "master", verbose = -2)) + expect_false(file.exists(file.path(d, "f4"))) + expect_s3_class(out[[1]], "try-error") + expect_true(getOption("Require.offlineMode")) +}) + +## What api.github.com/repos///git/refs sends, for branches given as c(name = sha). +fakeGitRefs <- function(branches) { + paste0("[", paste0( + '{"ref":"refs/heads/', names(branches), '","node_id":"x",', + '"url":"https://api.github.com/repos/acct/repo/git/refs/heads/', names(branches), '",', + '"object":{"sha":"', branches, '","type":"commit",', + '"url":"https://api.github.com/repos/acct/repo/git/commits/', branches, '"}}', collapse = ","), "]") +} + test_that("getSHAfromGitHub reads the commit of a branch from the repository's git refs", { localNoGitHubAccess() shaMain <- strrep("a", 40) @@ -574,9 +692,9 @@ test_that("getSHAfromGitHub reads the commit of a branch from the repository's g expect_error(f("acct", "private", "dev"), "does it need authentication") expect_false(file.exists(file.path(Require:::RequireGitHubCacheDir(), "listOfRepos_acct@private"))) local_mocked_bindings(getGitCredsToken = function() "token abc", - GETWauthThenNonAuth = function(url, ...) fakeResponse(url, '{"message":"Not Found"}', 404L), + curlGETauth = function(url, ...) fakeResponse(url, '{"message":"Not Found"}', 404L), .package = "Require") - skip_if_not_installed("httr") + skip_if_not_installed("curl") expect_error(f("acct", "private", "dev"), "Did you spell.+acct/private@dev") }) diff --git a/tests/testthat/test-31coverage7_testthat.R b/tests/testthat/test-31coverage7_testthat.R index 21a2cb55..5bc284dd 100644 --- a/tests/testthat/test-31coverage7_testthat.R +++ b/tests/testthat/test-31coverage7_testthat.R @@ -484,20 +484,20 @@ test_that(".downloadFileMasterMainAuth without a token takes a warning from the }) test_that(".downloadFileMasterMainAuth with a token retries a failed request, then returns its error", { - skip_if_not_installed("httr") + skip_if_not_installed("curl") skip_if_not_installed("gitcreds") localNoGitHubAccess7() d <- withr::local_tempdir() asked <- character() local_mocked_bindings( getGitCredsToken = function() "token abc", - GETWauthThenNonAuth = function(url, ...) { + curlGETauth = function(url, ...) { asked <<- c(asked, url) stop("Timeout was reached") }, .package = "Require") url <- "https://raw.githubusercontent.com/acct/pkgA/dev/DESCRIPTION" - ## it stopped with "is.response(x) is not TRUE" from httr::content(), on the first failure + ## it stopped with "is.response(x) is not TRUE" from reading the content of the try-error, on the first failure out <- Require:::.downloadFileMasterMainAuth(url, destfile = file.path(d, "DESCRIPTION"), verbose = -2) expect_s3_class(out[[1]], "try-error") expect_match(out[[1]], "Timeout was reached") @@ -1114,7 +1114,7 @@ test_that("setupOff says so when there is no .Rprofile to change", { withr::local_options(Require.verbose = 1) realExists <- base::file.exists notInHome <- function(...) if (any(startsWith(c(...), "~"))) FALSE else realExists(...) - ## not in an RStudio project: this stopped with rprojroot's "No root directory found" + ## not in an RStudio project: this used to stop with rprojroot's "No root directory found" expect_message(with_mocked_bindings(setupOff(verbose = 1), file.exists = notInHome, .package = "base"), "No .Rprofile file; nothing to do") ## the .Rprofile of the RStudio project the working directory is in is the one used @@ -1122,12 +1122,20 @@ test_that("setupOff says so when there is no .Rprofile to change", { writeLines("x <- 1", file.path(d, ".Rprofile")) dir.create(file.path(d, "sub")) withr::local_dir(file.path(d, "sub")) - skip_if_not_installed("rprojroot") expect_message(with_mocked_bindings(setupOff(verbose = 1), file.exists = notInHome, .package = "base"), "setLibPaths was not run to change the .Rprofile file; nothing to do") expect_identical(readLines(file.path(d, ".Rprofile")), "x <- 1") }) +test_that("findRprojDir finds the project folder from a subfolder, and NULL when there is none", { + d <- normalizePath(withr::local_tempdir(), winslash = "/") + dir.create(file.path(d, "a", "b"), recursive = TRUE) + expect_null(Require:::findRprojDir(file.path(d, "a", "b"))) + writeLines("Version: 1.0", file.path(d, "p.Rproj")) + expect_identical(Require:::findRprojDir(file.path(d, "a", "b")), d) + expect_identical(Require:::findRprojDir(d), d) +}) + test_that("a new .Rprofile is added to .gitignore, once, and says how to undo it", { d <- withr::local_tempdir() withr::local_dir(d)