
pipenv_config <- function(required_module) {

  pipfile <- pipenv_pipfile_path()
  if (!file.exists(pipfile))
    return(NULL)

  python <- pipenv_python(dirname(pipfile))
  python_config(python, required_module, forced = "Pipfile")

}

pipenv_pipfile_path <- function() {

  # check option
  pipfile <- getOption("reticulate.pipenv.pipfile")
  if (!is.null(pipfile))
    return(pipfile)

  # try default
  tryCatch(
    here::here("Pipfile"),
    error = function(e) ""
  )

}

pipenv_python <- function(root = NULL) {

  # validate that pipenv is available on the PATH
  if (!nzchar(Sys.which("pipenv")))
    stop("'pipenv' is not available")

  # move to root directory
  if (is.null(root))
    root <- tryCatch(here::here(), error = function(e) NULL)
  if (is.null(root))
    return(NULL)

  owd <- setwd(root)
  on.exit(setwd(owd), add = TRUE)

  # ask pipenv what the environment path is
  envpath <- system("pipenv --venv", intern = TRUE)
  status <- attr(envpath, "status") %||% 0L
  if (status != 0L) {
    fmt <- "'pipenv --venv' had status %i"
    stopf(fmt, status)
  }

  # get path to python
  virtualenv_python(envpath)

}
