R/dependencies-python.R

Defines functions pip_index_args merge_py_dependencies check_py_pin_conflicts warn_py_requirements_ignored resolve_py_dependencies cli_items uv_sources parse_pyproject_toml join_continued_lines parse_requirements_txt is_py_direct_reference py_normalize_name py_spec_name py_requirements read_py_requirements detect_py_dependencies

Documented in check_py_pin_conflicts detect_py_dependencies merge_py_dependencies parse_pyproject_toml parse_requirements_txt pip_index_args read_py_requirements resolve_py_dependencies

#' Detect Python package dependencies from requirements files
#'
#' Reads `requirements.txt` or `pyproject.toml` to determine
#' Python package dependencies. Does NOT parse import statements -- the
#' module-name-to-package-name mapping (e.g., `import cv2` maps to
#' `opencv-python`) makes import parsing unreliable.
#'
#' Prefers `requirements.txt` over `pyproject.toml` when both exist.
#' Warns if neither file is found, or if `pyproject.toml` has no packages in
#' the `dependencies` of its `[project]` table.
#'
#' @param appdir Character string. Path to the app directory.
#' @return Character vector of unique package names (sorted).
#' @keywords internal
detect_py_dependencies <- function(appdir) {
  read_py_requirements(appdir)$packages
}

#' Read an app's Python requirements
#'
#' Reads `requirements.txt`, or `pyproject.toml` when there is no
#' `requirements.txt`, and sorts each entry by whether pip can install it by
#' name from a package index. Warns as [detect_py_dependencies()] describes.
#'
#' @param appdir Character string. Path to the app directory.
#' @return A list with
#'   * `packages`: the package names, sorted and unique.
#'   * `requirements`: the requirement specs to install from an index, in
#'     file order, with their versions and environment markers.
#'   * `direct`: the entries that point at a URL, a version control
#'     repository or a path, which an index install cannot reach.
#'   * `ignored`: the pip option lines of `requirements.txt`, which are not
#'     read.
#'   * `indexed`: the names of the uv indexes that `[tool.uv.sources]` takes
#'     packages from, named by package.
#' @keywords internal
read_py_requirements <- function(appdir) {
  req_file <- file.path(appdir, "requirements.txt")
  pyproject_file <- file.path(appdir, "pyproject.toml")

  if (file.exists(req_file)) {
    return(parse_requirements_txt(req_file))
  }

  if (file.exists(pyproject_file)) {
    reqs <- parse_pyproject_toml(pyproject_file)
    if (length(reqs$packages) == 0) {
      cli::cli_warn(c(
        "No packages found in the {.code [project]} dependencies of {.path {pyproject_file}}",
        "i" = "Only the {.field dependencies} list of the {.code [project]} table is read",
        "i" = "List the app's packages there, in a {.file requirements.txt}, or in {.field dependencies.python.packages} of {.file {CONFIG_FILENAME}}"
      ))
    }
    return(reqs)
  }

  cli::cli_warn(c(
    "No {.file requirements.txt} or {.file pyproject.toml} found in {.path {appdir}}",
    "i" = "Create a {.file requirements.txt} to declare Python dependencies",
    "i" = "Without it, no packages will be installed for the app"
  ))
  py_requirements()
}

# The list read_py_requirements() returns. `named` holds the names of direct
# references that give one, such as "name @ url".
py_requirements <- function(requirements = character(0), direct = character(0),
                            ignored = character(0), indexed = character(0),
                            named = character(0)) {
  list(
    packages = sort(unique(c(py_spec_name(requirements), named))),
    requirements = unique(requirements),
    direct = direct,
    ignored = ignored,
    indexed = indexed
  )
}

# The package name of a PEP 508 spec ("pandas>=2.0", "shiny[theme]",
# "x @ url", or "shiny (>=1.0)" as Poetry 2 writes it).
py_spec_name <- function(spec) {
  trimws(sub("[>=<!~;@\\[,(].*", "", spec))
}

# A package name in its PEP 503 normalized form, for comparing names.
py_normalize_name <- function(name) {
  gsub("[-_.]+", "-", tolower(name))
}

# Whether a requirement points at a URL, a version control repository, or a
# path instead of naming a package on an index.
is_py_direct_reference <- function(spec) {
  # The requirement without its environment marker, which may hold a slash.
  requirement <- sub(";.*$", "", spec)
  grepl("^(git|hg|svn|bzr)\\+", spec) ||
    grepl("://", spec, fixed = TRUE) ||
    grepl("^file:", spec) ||
    # PEP 508 "name @ url", perhaps with extras.
    grepl("^[A-Za-z0-9][A-Za-z0-9._-]*\\s*(\\[[^]]*\\])?\\s*@", spec) ||
    # A path, as pip reads one: it starts like one or holds a separator.
    grepl("^(\\.|/|~|[A-Za-z]:[\\\\/])", spec) ||
    grepl("[/\\\\]", requirement) ||
    grepl("\\.(whl|zip|tar\\.gz|tgz|tar\\.bz2|tar\\.xz)$", spec)
}

#' Parse requirements.txt file
#'
#' Lines that end in a backslash continue on the next line, as pip reads
#' them, and a `#` at the start of a line or after a space starts a comment.
#' Options that follow a requirement, such as the `--hash` options that
#' `uv export` and `pip-compile` write, are dropped from it.
#'
#' @param path Character string. Path to requirements.txt.
#' @return A list as [read_py_requirements()] returns.
#' @keywords internal
parse_requirements_txt <- function(path) {
  lines <- join_continued_lines(readLines(path, warn = FALSE))
  requirements <- character(0)
  direct <- character(0)
  ignored <- character(0)
  named <- character(0)

  for (line in lines) {
    line <- trimws(sub("(^|\\s)#.*$", "", line))
    if (!nzchar(line)) next
    # An editable install is a path or a version control URL.
    if (grepl("^(-e|--editable)(\\s|=|$)", line)) {
      direct <- c(direct, line)
      next
    }
    if (startsWith(line, "-")) {
      ignored <- c(ignored, line)
      next
    }
    line <- trimws(sub("\\s--[A-Za-z].*$", "", line))
    if (is_py_direct_reference(line)) {
      direct <- c(direct, line)
      if (grepl("^[A-Za-z0-9][A-Za-z0-9._-]*\\s*(\\[[^]]*\\])?\\s*@", line)) {
        named <- c(named, py_spec_name(line))
      }
      next
    }
    requirements <- c(requirements, line)
  }

  py_requirements(requirements, direct = direct, ignored = ignored, named = named)
}

# Join each line that ends in a backslash to the line after it.
join_continued_lines <- function(lines) {
  out <- character(0)
  pending <- ""
  for (line in lines) {
    if (grepl("\\\\\\s*$", line)) {
      pending <- paste0(pending, sub("\\\\\\s*$", " ", line))
      next
    }
    out <- c(out, paste0(pending, line))
    pending <- ""
  }
  if (nzchar(pending)) out <- c(out, pending)
  out
}

#' Parse pyproject.toml dependencies section
#'
#' Simple parser for the `[project] dependencies` array in pyproject.toml,
#' where PEP 621 lists runtime dependencies. `dependencies` arrays in other
#' tables, such as Hatch's `[tool.hatch.envs.*]` environments, are ignored.
#' Entries may use double or single quotes, and `#` comments are skipped.
#' Does not handle complex TOML such as multi-line strings, a quoted
#' `["project"]` header, or a dotted `project.dependencies` key.
#'
#' A dependency that `[tool.uv.sources]` takes from git, a URL, a path, or a
#' workspace member is a direct reference, and one it takes from a named uv
#' index is listed in `indexed`.
#'
#' @param path Character string. Path to pyproject.toml.
#' @return A list as [read_py_requirements()] returns.
#' @keywords internal
parse_pyproject_toml <- function(path) {
  lines <- readLines(path, warn = FALSE)
  # readLines() drops a UTF-8 byte order mark only in a UTF-8 locale.
  if (length(lines)) lines[1] <- sub("^\xef\xbb\xbf", "", lines[1], useBytes = TRUE)
  specs <- character(0)

  # The strings, comments, and "]" on a line, in order. A double-quoted
  # string may hold backslash escapes; a single-quoted (literal) one cannot.
  # Matching whole strings keeps a "]" or "#" inside one, as in
  # "uvicorn[standard]", from ending the array or starting a comment.
  array_tokens <- function(s) {
    pattern <- "\"(?:[^\"\\\\]|\\\\.)*\"|'[^']*'|#.*|\\]"
    regmatches(s, gregexpr(pattern, s, perl = TRUE))[[1]]
  }

  in_project <- FALSE
  in_deps <- FALSE
  for (line in lines) {
    trimmed <- trimws(line)

    if (!in_deps) {
      # A table header such as [project] or [[tool.mypy.overrides]]: a
      # bracketed name alone on its line, perhaps with a comment. A line of a
      # multi-line string, such as "[Shiny] dashboard", is not one.
      if (grepl("^\\[\\[?[^][]*\\]\\]?\\s*(#.*)?$", trimmed)) {
        in_project <- grepl("^\\[\\s*project\\s*\\]\\s*(#.*)?$", trimmed)
        next
      }
      if (!in_project || !grepl("^dependencies\\s*=\\s*\\[", trimmed)) next
      in_deps <- TRUE
      # The rest of the opening line may already hold packages, e.g.
      # dependencies = ["shiny", "pandas"].
      trimmed <- sub("^dependencies\\s*=\\s*\\[", "", trimmed)
    }

    tokens <- array_tokens(trimmed)
    # The array ends at the first "]" outside a string or comment. It may
    # share a line with the last entry, or with the opening line in a
    # single-line array.
    closing <- match("]", tokens)
    if (!is.na(closing)) {
      tokens <- tokens[seq_len(closing - 1L)]
      in_deps <- FALSE
    }
    # The entries are the strings without their quotes; comments are dropped.
    strings <- tokens[!startsWith(tokens, "#")]
    entries <- trimws(substr(strings, 2L, nchar(strings) - 1L))
    specs <- c(specs, entries[nzchar(py_spec_name(entries))])
  }

  sources <- uv_sources(lines)
  requirements <- character(0)
  direct <- character(0)
  indexed <- character(0)
  named <- character(0)
  for (spec in specs) {
    name <- py_spec_name(spec)
    source <- sources[[py_normalize_name(name)]]
    if (is_py_direct_reference(spec)) {
      direct <- c(direct, spec)
      named <- c(named, name)
    } else if (!is.null(source) && !identical(source$kind, "index")) {
      direct <- c(direct, paste0(name, ", from ", source$kind, " in [tool.uv.sources]"))
      named <- c(named, name)
    } else {
      if (!is.null(source)) indexed[[name]] <- source$index
      requirements <- c(requirements, spec)
    }
  }

  py_requirements(requirements, direct = direct, indexed = indexed, named = named)
}

# Where [tool.uv.sources] takes each package from: a list named by
# normalized package name, each with `kind` (git, url, path, workspace, or
# index) and, for an index, `index`. Reads inline tables, arrays of them over
# several lines, and [tool.uv.sources.<name>] subtables.
uv_sources <- function(lines) {
  text <- list()
  table <- NULL
  open_array <- NULL
  for (line in lines) {
    trimmed <- trimws(sub("\\s+#[^\"']*$", "", line))
    if (!is.null(open_array)) {
      text[[open_array]] <- paste(text[[open_array]], trimmed)
      if (grepl("]\\s*$", trimmed)) open_array <- NULL
      next
    }
    if (grepl("^\\[\\[?[^][]*\\]\\]?$", trimmed)) {
      inner <- gsub("^\\[+\\s*|\\s*\\]+$", "", trimmed)
      table <- if (identical(inner, "tool.uv.sources")) {
        ""
      } else if (startsWith(inner, "tool.uv.sources.")) {
        py_normalize_name(gsub("[\"']", "", sub("^tool\\.uv\\.sources\\.", "", inner)))
      }
      next
    }
    if (is.null(table)) next
    if (nzchar(table)) {
      text[[table]] <- paste(text[[table]], trimmed)
      next
    }
    m <- regmatches(trimmed, regexec("^[\"']?([A-Za-z0-9._-]+)[\"']?\\s*=\\s*(.*)$", trimmed))[[1]]
    if (length(m) == 0) next
    name <- py_normalize_name(m[2])
    text[[name]] <- m[3]
    if (startsWith(m[3], "[") && !grepl("]\\s*$", m[3])) open_array <- name
  }

  lapply(text, function(t) {
    keys <- c("git", "url", "path", "workspace")
    found <- keys[vapply(keys, function(k) grepl(paste0("\\b", k, "\\s*="), t, perl = TRUE), logical(1))]
    if (length(found)) return(list(kind = found[1]))
    index <- regmatches(t, regexec("\\bindex\\s*=\\s*[\"']([^\"']+)[\"']", t, perl = TRUE))[[1]]
    if (length(index)) return(list(kind = "index", index = index[2]))
    NULL
  })
}

# One bullet per element of a vector, as cli markup that reads the element
# from the calling function's frame (`fmt` names it with %1$d as its index).
cli_items <- function(fmt, n, bullet = "*") {
  stats::setNames(sprintf(fmt, seq_len(n)), rep(bullet, n))
}

#' Resolve an app's Python dependencies for an export
#'
#' Reads the app's requirements and merges them with the configured
#' packages. Stops when a requirement points at a URL, a version control
#' repository, or a path, since the built app installs its packages by name
#' from a package index. Warns about pip options in `requirements.txt`, which
#' are not read, and about packages that `[tool.uv.sources]` takes from a uv
#' index.
#'
#' When `dependencies.auto_detect` is off the app's requirements are not
#' installed, so they are not read or checked either.
#'
#' @param appdir Character string. Path to the app directory.
#' @param config_deps List from config$dependencies.
#' @param reqs List. The app's requirements, as [read_py_requirements()]
#'   reads them.
#' @return List with `packages`, `requirements`, and `index_urls`, as
#'   [merge_py_dependencies()] returns.
#' @keywords internal
resolve_py_dependencies <- function(appdir, config_deps, reqs = read_py_requirements(appdir)) {
  if (!isTRUE(config_deps$auto_detect %||% TRUE)) {
    return(merge_py_dependencies(character(0), config_deps))
  }

  if (length(reqs$direct) > 0) {
    n <- length(reqs$direct)
    cli::cli_abort(c(
      "The built app installs Python packages by name from a package index, so it cannot install {cli::qty(n)}{?this requirement/these requirements} of {.path {appdir}}:",
      cli_items("{.code {reqs$direct[[%1$d]]}}", n),
      "i" = "Install a released version from an index by name, or publish a wheel to an index and list that index in {.field dependencies.python.index_urls} of {.file {CONFIG_FILENAME}}.",
      "i" = "If the app runs without {cli::qty(n)}{?it/them}, set {.field dependencies.auto_detect} to {.val false} and list the packages it needs under {.field dependencies.python.packages}."
    ), class = "shinyelectron_python_direct_reference")
  }

  warn_py_requirements_ignored(reqs$ignored, appdir)

  if (length(reqs$indexed) > 0) {
    indexed <- reqs$indexed
    cli::cli_warn(c(
      "{.file pyproject.toml} takes {cli::qty(length(indexed))}{?a package/packages} from a uv index:",
      cli_items("{.pkg {names(indexed)[[%1$d]]}} from {.val {indexed[[%1$d]]}}", length(indexed)),
      "i" = "The built app installs from {.field dependencies.python.index_urls} of {.file {CONFIG_FILENAME}}, so list each index's URL there."
    ), class = "shinyelectron_python_uv_index")
  }

  merge_py_dependencies(reqs$packages, config_deps, requirements = reqs$requirements)
}

# Warn about the pip option lines of a requirements.txt, which are not read.
# The advice depends on what was skipped: a file that -r or -c names, or a
# package index.
warn_py_requirements_ignored <- function(ignored, appdir) {
  n <- length(ignored)
  if (n == 0) return(invisible())
  includes <- any(grepl("^(-[rc]|--requirement|--constraint)", ignored))
  indexes <- any(grepl("^(-[if]|--index-url|--extra-index-url|--find-links)", ignored))
  cli::cli_warn(c(
    "Skipped {cli::qty(n)}{?a pip option/pip options} in the {.file requirements.txt} of {.path {appdir}}:",
    cli_items("{.code {ignored[[%1$d]]}}", n),
    if (includes) c("i" = "The files that {.code -r} and {.code -c} name are not read. Put their packages and pins in this {.file requirements.txt}, or list the packages under {.field dependencies.python.packages} of {.file {CONFIG_FILENAME}}."),
    if (indexes) c("i" = "List package indexes in {.field dependencies.python.index_urls} of {.file {CONFIG_FILENAME}}.")
  ), class = "shinyelectron_python_requirements_ignored")
}

#' Stop when apps pin one Python package to different versions
#'
#' The apps of a bundled suite share one Python library, and pip installs
#' none of their packages when two exact pins of a package disagree. Pins
#' under different environment markers are left to pip, since both can hold.
#'
#' @param specs_by_app Named list. Each app's requirement specs, named by the
#'   app's name.
#' @return Invisibly, `NULL`.
#' @keywords internal
check_py_pin_conflicts <- function(specs_by_app) {
  pins <- do.call(rbind, lapply(names(specs_by_app), function(app) {
    specs <- as.character(unlist(specs_by_app[[app]]))
    requirement <- sub(";.*$", "", specs)
    # An exact pin: "==" and a whole version, not "===" or a "2.2.*" range.
    pinned <- regmatches(requirement, regexec(
      "(?<![=!<>~])==(?!=)\\s*([A-Za-z0-9._+!-]+)\\s*(,|$)", requirement, perl = TRUE
    ))
    is_pin <- lengths(pinned) > 0
    data.frame(
      app = rep(app, sum(is_pin)),
      name = py_normalize_name(py_spec_name(specs[is_pin])),
      marker = trimws(sub("^[^;]*;?", "", specs[is_pin])),
      version = vapply(pinned[is_pin], function(m) m[[2]], character(1)),
      stringsAsFactors = FALSE
    )
  }))
  if (is.null(pins) || nrow(pins) == 0) return(invisible())

  groups <- split(pins, list(pins$name, pins$marker), drop = TRUE)
  groups <- Filter(function(g) length(unique(g$version)) > 1, groups)
  if (length(groups) == 0) return(invisible())

  conflicts <- vapply(groups, function(g) {
    g <- g[!duplicated(g[c("app", "version")]), ]
    paste0(g$name[[1]], ": ", paste0("==", g$version, " in ", g$app, collapse = ", "))
  }, character(1))
  n <- length(conflicts)
  cli::cli_abort(c(
    "The apps of a bundled suite share one Python library, so they cannot pin different versions of {cli::qty(n)}{?a package/packages}:",
    cli_items("{conflicts[[%1$d]]}", n, bullet = "x"),
    "i" = "Give the apps the same pin, or list the suite's packages in a {.file requirements.txt} at the suite root."
  ), class = "shinyelectron_python_pin_conflict")
}

#' Merge detected Python dependencies with config declarations
#'
#' @param detected Character vector of detected package names.
#' @param config_deps List from config$dependencies.
#' @param requirements Character vector. The requirement specs behind
#'   `detected`, with their versions and environment markers.
#' @return List with `packages` (sorted package names), `requirements` (the
#'   specs to install) and `index_urls` (list).
#' @keywords internal
merge_py_dependencies <- function(detected, config_deps, requirements = detected) {
  index_urls <- config_deps$python$index_urls %||%
    SHINYELECTRON_DEFAULTS$dependencies$python$index_urls

  declared <- unlist(config_deps$python$packages %||% list())
  extra <- unlist(config_deps$extra_packages %||% list())
  added <- c(declared, extra)

  if (isTRUE(config_deps$auto_detect %||% TRUE)) {
    packages <- sort(unique(c(detected, py_spec_name(added))))
    requirements <- unique(c(requirements, added))
  } else {
    packages <- sort(unique(py_spec_name(added)))
    requirements <- unique(added)
  }

  list(packages = packages, requirements = requirements, index_urls = index_urls)
}

#' pip arguments for a set of package indexes
#'
#' @param index_urls Character vector or list. Package index URLs; the
#'   first is the main index and the rest are extra ones.
#' @return Character vector of pip arguments.
#' @keywords internal
pip_index_args <- function(index_urls) {
  urls <- unlist(index_urls)
  urls <- urls[nzchar(urls)]
  if (length(urls) == 0) urls <- "https://pypi.org/simple"
  extra <- urls[-1]
  c("-i", urls[1], as.vector(rbind(rep("--extra-index-url", length(extra)), extra)))
}

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.