Debian Codegraph @

R/python-conda.R

raw
1
2 renv_python_conda_select <- function(name, version = NULL) {
3
4 # get python package
5 version <- version %||% Sys.getenv("RENV_CONDA_PYTHON_VERSION", unset = "3.7")
6 packages <- paste("python", version, sep = "=")
7
8 # handle paths (as opposed to environment names)
9 if (grepl("[/\\\\]", name)) {
10 if (!file.exists(name))
11 return(reticulate::conda_create(envname = name, packages = packages))
12 return(renv_python_exe(name))
13 }
14
15 # check for an existing conda environment
16 envs <- reticulate::conda_list()
17 idx <- which(name == envs$name)
18 if (length(idx))
19 return(envs$python[[idx]])
20
21 # no environment exists; create it
22 reticulate::conda_create(envname = name, packages = packages)
23
24 }
25
26 renv_python_conda_export_path <- function(project) {
27
28 # check override
29 override <- renv_paths_override("CONDA_EXPORT")
30 if (!is.null(override))
31 return(override)
32
33 # use default
34 file.path(project, "environment.yml")
35
36 }
37
38 # TODO: support prompt
39 renv_python_conda_snapshot <- function(project, prompt, python) {
40
41 renv_scope_wd(project)
42
43 path <- renv_python_conda_export_path(project = project)
44
45 # find the root of the associated conda environment
46 lockfile <- renv_lockfile_load(project = project)
47 name <- lockfile$Python$Name %||% renv_python_envpath(project, "conda", version)
48 python <- renv_python_conda_select(name)
49 info <- renv_python_info(python)
50 prefix <- info$root
51
52 conda <- reticulate::conda_binary()
53 args <- c(
54 "env", "export",
55 "--prefix", renv_shell_path(prefix),
56 "--file", renv_shell_path(path)
57 )
58
59 output <- if (renv_tests_running()) FALSE else ""
60 system2(conda, args, stdout = output, stderr = output)
61
62 writef("- Wrote Python packages to '%s'.", renv_path_aliased(path))
63 return(TRUE)
64 }
65
66 # TODO: support prompt
67 renv_python_conda_restore <- function(project, prompt, python) {
68
69 renv_scope_wd(project)
70
71 path <- renv_python_conda_export_path(project = project)
72
73 # find the root of the associated conda environment
74 lockfile <- renv_lockfile_load(project = project)
75 name <- lockfile$Python$Name %||% renv_python_envpath(project, "conda", version)
76 python <- renv_python_conda_select(name)
77 info <- renv_python_info(python)
78 prefix <- info$root
79
80 conda <- reticulate::conda_binary()
81 command <- if (file.exists(prefix)) "update" else "create"
82 args <- c(
83 "env", command,
84 "--prefix", renv_shell_path(prefix),
85 "--file", renv_shell_path(path)
86 )
87
88 output <- if (renv_tests_running()) FALSE else ""
89 system2(conda, args, stdout = output, stderr = output)
90
91 return(TRUE)
92
93 }