R/install-r.R

Defines functions generate_runtime_manifest r_expected_sha256 install_r_portable portable_r_env r_executable r_is_installed r_install_path r_download_url r_portable_latest_version github_latest_release_tag r_latest_version

Documented in generate_runtime_manifest github_latest_release_tag install_r_portable portable_r_env r_download_url r_executable r_expected_sha256 r_install_path r_is_installed r_latest_version r_portable_latest_version

#' Get the latest R release version
#'
#' Queries the R API for the current release version.
#'
#' @return Character string. The latest R version (e.g., "4.4.1").
#' @keywords internal
r_latest_version <- function() {
  tryCatch({
    url <- "https://api.r-hub.io/rversions/r-release"
    content <- readLines(url, warn = FALSE)
    parsed <- jsonlite::fromJSON(paste(content, collapse = ""))
    parsed$version
  }, error = function(e) {
    cli::cli_abort(c(
      "Failed to query latest R version",
      "x" = "Error: {e$message}",
      "i" = "Check your internet connection"
    ))
  })
}

#' Find the tag of a GitHub repository's newest release
#'
#' Reads the `location` header that `https://github.com/<repo>/releases/latest`
#' redirects with and takes what follows `/releases/tag/`. This page redirect
#' is not subject to the hourly request limit of GitHub's API. The lookup
#' never throws and never warns.
#'
#' @param repo Character string. The repository, as `"owner/name"`.
#' @param timeout Number. Seconds the request may take.
#' @return Character string. The tag (e.g., `"v4.6.2"`), or `NULL` when it
#'   cannot be found.
#' @keywords internal
github_latest_release_tag <- function(repo, timeout = 5) {
  url <- paste0("https://github.com/", repo, "/releases/latest")
  headers <- tryCatch(
    curlGetHeaders(url, redirect = FALSE, timeout = timeout),
    warning = function(w) NULL,
    error = function(e) NULL
  )
  location <- grep("^location:", headers, ignore.case = TRUE, value = TRUE)
  if (length(location) == 0) {
    return(NULL)
  }
  target <- trimws(sub("^location:", "", location[1], ignore.case = TRUE))
  if (!grepl("/releases/tag/.", target)) {
    return(NULL)
  }
  sub(".*/releases/tag/", "", target)
}

#' Get the newest R version available as a portable-r build
#'
#' The bundled and auto-download strategies download R from the portable-r
#' release repos, which can lag behind the newest R release (so the latest R
#' from [r_latest_version()] may have no portable build yet, yielding a 404).
#' For `"win"` and `"mac"` this returns the newest release of the platform's
#' portable-r repo, found with [github_latest_release_tag()]. For any other
#' platform it returns [r_latest_version()], given five seconds.
#'
#' When the lookup fails, or does not give a `major.minor.patch` version, this
#' returns `SHINYELECTRON_DEFAULTS$runtime_versions$r` instead and says so in a
#' message of class `shinyelectron_r_version_fallback`. It never aborts.
#'
#' @param platform Character string. Target platform: "win", "mac", "linux".
#'   `NULL` for the build machine.
#' @return Character string. The newest portable R version, or the fallback.
#' @keywords internal
r_portable_latest_version <- function(platform = NULL) {
  platform <- platform %||% detect_current_platform()
  repo <- switch(platform,
    "win" = "portable-r/portable-r-windows",
    "mac" = "portable-r/portable-r-macos",
    NULL
  )

  version <- if (is.null(repo)) {
    # readLines() waits as long as the timeout option, 60 seconds by default.
    old <- options(timeout = 5)
    on.exit(options(old), add = TRUE)
    tryCatch(suppressWarnings(r_latest_version()), error = function(e) NULL)
  } else {
    sub("^v", "", github_latest_release_tag(repo) %||% "")
  }

  if (!is.character(version) || length(version) != 1 ||
      !grepl("^\\d+\\.\\d+\\.\\d+$", version)) {
    fallback <- SHINYELECTRON_DEFAULTS$runtime_versions$r
    cli::cli_inform(
      "Could not look up the newest R, so using R {fallback}.",
      class = "shinyelectron_r_version_fallback"
    )
    return(fallback)
  }
  version
}

#' Construct download URL for portable R
#'
#' Generates the download URL for an R build from CRAN.
#'
#' @param version Character string. R version (e.g., "4.4.0").
#' @param platform Character string. Target platform: "win", "mac", "linux".
#' @param arch Character string. Target architecture: "x64", "arm64".
#' @return Character string. Download URL.
#' @keywords internal
r_download_url <- function(version, platform = NULL, arch = NULL) {
  platform <- platform %||% detect_current_platform()
  arch <- arch %||% detect_current_arch()

  switch(platform,
    "win" = {
      win_arch <- if (arch == "arm64") "aarch64" else "x64"
      paste0("https://github.com/portable-r/portable-r-windows/releases/download/v",
             version, "/portable-r-", version, "-win-", win_arch, ".zip")
    },
    "mac" = {
      mac_arch <- if (arch == "arm64") "arm64" else "x86_64"
      paste0("https://github.com/portable-r/portable-r-macos/releases/download/v",
             version, "/portable-r-", version, "-macos-", mac_arch, ".tar.gz")
    },
    "linux" = {
      cli::cli_abort(c(
        "Portable R for Linux is not yet supported for bundled/auto-download strategies",
        "i" = "Use {.val system} or {.val container} runtime strategy on Linux"
      ))
    },
    cli::cli_abort("Unsupported platform: {.val {platform}}")
  )
}

#' Get the installation path for a cached R version
#'
#' @param version Character string. R version.
#' @param platform Character string. Platform (default: current).
#' @param arch Character string. Architecture (default: current).
#' @return Character string. Path to the cached R installation.
#' @keywords internal
r_install_path <- function(version, platform = NULL, arch = NULL) {
  platform <- platform %||% detect_current_platform()
  arch <- arch %||% detect_current_arch()
  path.expand(cache_r_path(version, platform, arch))
}

#' Check if a portable R version is installed
#'
#' @param version Character string. R version to check.
#' @param platform Character string. Platform (default: current).
#' @param arch Character string. Architecture (default: current).
#' @return Logical.
#' @keywords internal
r_is_installed <- function(version, platform = NULL, arch = NULL) {
  path <- r_install_path(version, platform, arch)
  fs::dir_exists(path)
}

#' Get the path to the Rscript executable in a cached installation
#'
#' @param version Character string. R version.
#' @param platform Character string. Platform (default: current).
#' @param arch Character string. Architecture (default: current).
#' @return Character string or NULL. Path to Rscript, or NULL if not found.
#' @keywords internal
r_executable <- function(version, platform = NULL, arch = NULL) {
  platform <- platform %||% detect_current_platform()
  arch <- arch %||% detect_current_arch()
  install_path <- r_install_path(version, platform, arch)

  candidates <- character(0)

  if (platform == "win") {
    win_arch <- if (arch == "arm64") "aarch64" else "x64"
    portable_dir <- paste0("portable-r-", version, "-win-", win_arch)
    candidates <- c(
      fs::path(install_path, portable_dir, "bin", "Rscript.exe"),
      fs::path(install_path, "bin", "Rscript.exe")
    )
  } else if (platform == "mac") {
    mac_arch <- if (arch == "arm64") "arm64" else "x86_64"
    portable_dir <- paste0("portable-r-", version, "-macos-", mac_arch)
    candidates <- c(
      fs::path(install_path, portable_dir, "bin", "Rscript"),
      fs::path(install_path, "bin", "Rscript")
    )
  } else {
    candidates <- c(
      fs::path(install_path, "bin", "Rscript")
    )
  }

  for (exe_path in candidates) {
    if (fs::file_exists(exe_path)) return(exe_path)
  }
  NULL
}

#' Environment for processes of a portable R
#'
#' The caller's environment without `R_ENVIRON` and `R_PROFILE`, so a portable
#' R reads its own site files instead of site files chosen for the calling R
#' (callr sets both for the R it starts, and a user can set them too). On macOS
#' the portable R's `Rprofile.site` rewrites the shared-library references of
#' the binary packages it installs, which is what lets them load. The user's
#' environ file and profile and every other variable are kept.
#'
#' @return Named character vector for the `env` argument of
#'   [processx::run()].
#' @keywords internal
portable_r_env <- function() {
  env <- Sys.getenv()
  env <- stats::setNames(as.character(env), names(env))
  key <- if (.Platform$OS.type == "windows") toupper else identity
  env[!key(names(env)) %in% c("R_ENVIRON", "R_PROFILE")]
}

#' Install a portable R distribution
#'
#' Downloads and caches a portable R build. Follows the same pattern
#' as [install_nodejs()].
#'
#' @param version Character string. R version to install. If NULL, installs latest.
#' @param platform Character string. Target platform.
#' @param arch Character string. Target architecture.
#' @param force Logical. Whether to reinstall if already cached.
#' @param verbose Logical. Whether to show progress.
#' @return Character string. Path to the installed R directory.
#'
#' @seealso [install_python_standalone()], [install_nodejs()] for other runtime installers;
#'   [r_executable()] to find the installed Rscript path.
#'
#' @examplesIf interactive()
#' # Install latest R release
#' install_r_portable()
#'
#' # Install specific version for a target platform
#' install_r_portable(version = "4.4.0", platform = "win", arch = "x64")
#'
#' @export
install_r_portable <- function(version = NULL, platform = NULL, arch = NULL,
                      force = FALSE, verbose = TRUE) {
  platform <- platform %||% detect_current_platform()
  arch <- arch %||% detect_current_arch()

  if (is.null(version)) {
    if (verbose) cli::cli_alert_info("Querying latest available R release...")
    version <- r_portable_latest_version(platform)
  }

  if (!grepl("^\\d+\\.\\d+\\.\\d+$", version)) {
    cli::cli_abort(c(
      "Invalid R version format: {.val {version}}",
      "i" = "Expected format: major.minor.patch (e.g., 4.4.0)"
    ))
  }

  if (verbose) {
    cli::cli_alert_info("Platform: {platform}, Architecture: {arch}")
  }

  expected_sha256 <- r_expected_sha256(version, platform, arch)
  if (is.null(expected_sha256) && verbose) {
    cli::cli_warn(c(
      "Could not fetch the published SHA-256 checksum for R {version}",
      "i" = "Continuing without checksum verification"
    ))
  }

  download_and_extract_portable_tool(
    label = "R",
    version = version,
    install_path = r_install_path(version, platform, arch),
    download_url = r_download_url(version, platform, arch),
    executable_finder = function() r_executable(version, platform, arch),
    force = force,
    is_installed = r_is_installed(version, platform, arch),
    expected_sha256 = expected_sha256,
    verbose = verbose
  )
}

#' Published SHA-256 checksum for a portable R archive
#'
#' Portable R publishes a per-asset `.sha256` sidecar next to each release
#' archive (`<archive-url>.sha256`). Returns `NULL` when unavailable so the
#' caller can continue without verification.
#'
#' @inheritParams r_download_url
#' @return Character SHA-256 hash, or `NULL`.
#' @keywords internal
r_expected_sha256 <- function(version, platform = NULL, arch = NULL) {
  url <- r_download_url(version, platform, arch)
  fetch_published_sha256(paste0(url, ".sha256"))
}

#' Generate a runtime manifest for auto-download
#'
#' Creates a JSON manifest that the Electron app reads on first launch
#' to download the R runtime.
#'
#' @param version Character string. R version.
#' @param platform Character string. Target platform.
#' @param arch Character string. Target architecture.
#' @return Character string. JSON content.
#' @keywords internal
generate_runtime_manifest <- function(version, platform = NULL, arch = NULL) {
  platform <- platform %||% detect_current_platform()
  arch <- arch %||% detect_current_arch()

  download_url <- r_download_url(version, platform, arch)

  manifest <- list(
    schema_version = MANIFEST_SCHEMA_VERSION,
    language = "r",
    version = version,
    download_url = download_url,
    install_path = paste0("~/.shinyelectron/runtimes/R-", version),
    platform = platform,
    arch = arch
  )

  # Embed the published SHA-256 so the Electron runtime-downloader verifies the
  # archive before extraction on first launch. Omitted when unavailable; the
  # downloader treats an absent hash as "verification unavailable".
  sha256 <- r_expected_sha256(version, platform, arch)
  if (!is.null(sha256)) manifest$sha256 <- sha256

  jsonlite::toJSON(manifest, pretty = TRUE, auto_unbox = TRUE)
}

Try the shinyelectron package in your browser

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

shinyelectron documentation built on Dec. 3, 2026, 9:07 a.m.