Debian Codegraph @

R/python.R

raw
1
2 renv_python_resolve <- function(python = NULL) {
3
4 # if Python was explicitly supplied, use it
5 if (!is.null(python)) {
6
7 resolved <- Sys.which(renv_path_canonicalize(python))
8 if (nzchar(resolved))
9 return(resolved)
10
11 stopf("'%s' does not refer to a valid python interpreter", python)
12
13 }
14
15 # in interactive sessions, ask user what version of python they'd like to use
16 if (interactive()) {
17
18 python <- renv_python_select()
19
20 fmt <- "- Selected %s [Python %s]."
21 writef(fmt, renv_path_pretty(python), renv_python_version(python))
22
23 return(path.expand(python))
24
25 }
26
27 # check environment variables
28 envvars <- c("RETICULATE_PYTHON", "RETICULATE_PYTHON_ENV")
29 for (envvar in envvars) {
30 val <- Sys.getenv(envvar, unset = NA)
31 if (!is.na(val) && file.exists(val))
32 return(val)
33 }
34
35 # check on the PATH (prefer Python 3)
36 for (binary in c("python3", "python")) {
37 python <- Sys.which(binary)
38 if (nzchar(python))
39 return(python)
40 }
41
42 stopf("could not locate Python (not available on the PATH)")
43
44 }
45
46 renv_python_find <- function(version, path = NULL) {
47 renv_python_find_impl(version, path)
48 }
49
50 renv_python_find_impl <- function(version, path = NULL) {
51
52 # if we've been given the name of an environment,
53 # check to see if it's already been initialized
54 # and use the associated copy of Python if possible
55 if (!is.null(path) && file.exists(path)) {
56 python <- catch(renv_python_exe(path))
57 if (!inherits(python, "error"))
58 return(python)
59 }
60
61 # try to find a compatible version of python
62 pythons <- renv_python_discover()
63 if (length(pythons) == 0) {
64
65 fmt <- lines(
66 "project requested Python %s, but no compatible Python installation could be found.",
67 "renv's Python integration will be disabled in this session.",
68 "See `?renv::use_python` for more details."
69 )
70
71 stopf(fmt, version)
72
73 }
74
75 # read python versions
76 pyversions <- map_chr(pythons, function(python) {
77 tryCatch(
78 renv_python_version(python),
79 error = function(e) "0.0.0"
80 )
81 })
82
83 # try to find a compatible version
84 renv_version_match(pyversions, version)
85
86 }
87
88 renv_python_exe <- function(path) {
89
90 # if this already looks like a Python executable, use it directly
91 info <- renv_file_info(path)
92 if (identical(info$isdir, FALSE) && startsWith(basename(path), "python"))
93 return(renv_path_canonicalize(path))
94
95 # otherwise, attempt to infer the Python executable type
96 info <- renv_python_info(path)
97 if (!is.null(info$python))
98 return(renv_path_canonicalize(info$python))
99
100 fmt <- "failed to find Python executable associated with path %s"
101 stopf(fmt, renv_path_pretty(path))
102
103 }
104
105 renv_python_version <- function(python) {
106
107 filebacked(
108 context = "renv_python_version",
109 path = renv_path_normalize(python),
110 callback = renv_python_version_impl
111 )
112
113 }
114
115 renv_python_version_impl <- function(python) {
116 python <- renv_path_canonicalize(python)
117 code <- "from platform import python_version; print(python_version())"
118 args <- c("-c", shQuote(code))
119 action <- "reading Python version"
120 renv_system_exec(python, args, action)
121 }
122
123 renv_python_info <- function(python) {
124
125 found <- renv_file_find(python, function(path) {
126
127 # check for virtual environment files
128 virtualenv <-
129 file.exists(file.path(path, "pyvenv.cfg")) ||
130 file.exists(file.path(path, ".Python")) ||
131 file.exists(file.path(path, "bin/activate_this.py"))
132
133 if (virtualenv) {
134 suffix <- if (renv_platform_windows()) "Scripts/python.exe" else "bin/python"
135 python <- file.path(path, suffix)
136 return(list(python = python, type = "virtualenv", root = path))
137 }
138
139 # check for conda-meta
140 condaenv <-
141 file.exists(file.path(path, "conda-meta")) &&
142 !file.exists(file.path(path, "condabin"))
143
144 if (condaenv) {
145 suffix <- if (renv_platform_windows()) "python.exe" else "bin/python"
146 python <- file.path(path, suffix)
147 return(list(python = python, type = "conda", root = path))
148 }
149
150 })
151
152 if (!is.null(found))
153 return(found)
154
155 if (file.exists(python))
156 list(python = python, type = "system", root = python)
157
158 }
159
160 renv_python_type <- function(python) {
161 info <- renv_python_info(python)
162 info$type
163 }
164
165 renv_python_action <- function(action, prompt, project) {
166
167 python <- Sys.getenv("RENV_PYTHON", unset = NA)
168 if (is.na(python) || !file.exists(python))
169 return(NULL)
170
171 type <- renv_python_type(python)
172 if (is.null(type))
173 return(NULL)
174
175 if (type == "conda" && !requireNamespace("reticulate", quietly = TRUE))
176 return(NULL)
177
178 action(python, type, prompt, project)
179
180 }
181
182 renv_python_snapshot <- function(project, prompt) {
183 renv_python_action(
184 renv_python_snapshot_impl,
185 prompt = prompt,
186 project = project
187 )
188 }
189
190 renv_python_snapshot_impl <- function(python, type, prompt, project) {
191
192 switch(type,
193 virtualenv = renv_python_virtualenv_snapshot(project, prompt, python),
194 conda = renv_python_conda_snapshot(project, prompt, python)
195 )
196
197 }
198
199 renv_python_restore <- function(project, prompt) {
200 renv_python_action(
201 renv_python_restore_impl,
202 prompt = prompt,
203 project = project
204 )
205 }
206
207 renv_python_restore_impl <- function(python, type, prompt, project) {
208
209 case(
210 type == "virtualenv" ~ renv_python_virtualenv_restore(project, prompt, python),
211 type == "conda" ~ renv_python_conda_restore(project, prompt, python)
212 )
213
214 }
215
216 renv_python_envpath_virtualenv <- function(version) {
217 sprintf("python/virtualenvs/renv-python-%s", renv_version_maj_min(version))
218 }
219
220 renv_python_envpath_condaenv <- function(version) {
221 "python/condaenvs/renv-python"
222 }
223
224 renv_python_envpath <- function(project, type, version = NULL) {
225
226 suffix <- case(
227 type == "virtualenv" ~ renv_python_envpath_virtualenv(version),
228 type == "conda" ~ renv_python_envpath_condaenv(version),
229 ~ stopf("internal error: unrecognized environment type '%s'", type)
230 )
231
232 renv_paths_renv(suffix, project = project)
233
234 }
235
236 renv_python_envname <- function(project, path, type) {
237
238 # check for a project-local environment
239 if (renv_path_within(path, project)) {
240 stem <- substring(path, nchar(project) + 2L)
241 path <- paste(".", stem, sep = "/")
242 return(path)
243 }
244
245 bn <- basename(path)
246
247 # check for file within virtualenv
248 ok <-
249 type == "virtualenv" &&
250 identical(renv_python_virtualenv_path(bn), path)
251
252 if (ok)
253 return(bn)
254
255 # check for named conda environment
256 ok <-
257 type == "conda" &&
258 bn %in% reticulate::conda_list()$name
259
260 if (ok)
261 return(bn)
262
263 # doesn't match any known named environments; return full path
264 path
265
266 }
267
268 renv_python_discover <- function() {
269
270 all <- stack()
271
272 # find python in some pre-determined root directories
273 roots <- c(
274 getOption("renv.python.root"),
275 Sys.getenv("WORKON_HOME", "~/.virtualenvs"),
276 "/opt/python",
277 "/opt/local/python",
278 "~/opt/python",
279 file.path(renv_pyenv_root(), "versions")
280 )
281
282 for (root in roots) {
283 versions <- sort(list.files(root, full.names = TRUE), decreasing = TRUE)
284 exts <- if (renv_platform_windows()) "Scripts/python.exe" else "bin/python"
285 pythons <- file.path(versions, exts)
286 all$push(pythons)
287 }
288
289 # find Homebrew python
290 if (renv_platform_macos()) {
291
292 homebrew <- renv_homebrew_root()
293 roots <- sort(list.files(
294 path = file.path(homebrew, "opt"),
295 pattern = "^python@[[:digit:]]+[.][[:digit:]]+$",
296 full.names = TRUE
297 ), decreasing = TRUE)
298
299 for (root in roots) {
300
301 # homebrew python doesn't install bin/python, so we need
302 # to be a little bit more clever here
303 exes <- list.files(
304 path = file.path(root, "bin"),
305 pattern = "^python[[:digit:]]+[.][[:digit:]]+$",
306 full.names = TRUE
307 )
308
309 if (length(exes))
310 all$push(exes[[1L]])
311
312 }
313
314 }
315
316 # find Windows python installations
317 if (renv_platform_windows()) {
318
319 sd <- Sys.getenv("SYSTEMDRIVE", unset = "C:")
320 roots <- file.path(sd, c("", "Program Files"))
321
322 lad <- Sys.getenv("LOCALAPPDATA", unset = NA)
323 if (!is.na(lad))
324 roots <- c(roots, file.path(lad, "Programs/Python"))
325
326 dirs <- list.files(
327 path = roots,
328 pattern = "^Python",
329 full.names = TRUE
330 )
331
332 if (length(dirs)) {
333 exes <- file.path(dirs, "python.exe")
334 pythons <- renv_path_normalize(exes)
335 all$push(pythons)
336 }
337
338 }
339
340 # find Python installations on the PATH
341 path <- Sys.getenv("PATH", unset = "")
342 splat <- strsplit(path, .Platform$path.sep, fixed = TRUE)[[1L]]
343 for (entry in splat) {
344 for (exe in c("python3", "python")) {
345 python <- Sys.which(file.path(entry, exe))
346 if (nzchar(python))
347 all$push(python)
348 }
349 }
350
351 # collect discovered pythons as vector
352 pythons <- unlist(all$data(), recursive = FALSE, use.names = TRUE)
353
354 # don't include /usr/bin/python on macOS (too old)
355 if (renv_platform_macos())
356 pythons <- setdiff(pythons, "/usr/bin/python")
357
358 # get list of pythons
359 pythons <- renv_path_canonicalize(pythons[file.exists(pythons)])
360
361 # don't include WindowsApps
362 if (renv_platform_windows())
363 pythons <- grep("/WindowsApps/", pythons, invert = TRUE, value = TRUE)
364
365 unique(pythons)
366
367 }
368
369 renv_python_select_error <- function() {
370
371 lines <- c(
372 "renv was unable to find any Python installations on your machine.",
373 if (renv_platform_windows())
374 "Consider installing Python from https://www.python.org/downloads/windows/.",
375 if (renv_platform_macos())
376 "Consider installing Python from https://www.python.org/downloads/mac-osx/."
377 )
378
379 stop(paste(lines, collapse = "\n"))
380
381 }
382
383 renv_python_select <- function(candidates = NULL) {
384
385 candidates <- renv_path_aliased(candidates %||% renv_python_discover())
386 if (empty(candidates))
387 return(renv_python_select_error())
388
389 title <- "Please select a version of Python to use with this project:"
390 selection <- tryCatch(
391 utils::select.list(candidates, title = title, graphics = FALSE),
392 interrupt = identity
393 )
394
395 if (selection %in% "" || inherits(selection, "interrupt"))
396 stop("operation canceled by user")
397
398 return(path.expand(selection))
399
400 }
401
402 renv_python_module_available <- function(python, module) {
403 python <- renv_path_canonicalize(python)
404 command <- paste("import", module)
405 args <- c("-c", shQuote(command))
406 status <- system2(python, args, stdout = FALSE, stderr = FALSE)
407 identical(status, 0L)
408 }
409
410 renv_python_active <- function() {
411
412 python <- Sys.getenv("RENV_PYTHON", unset = NA)
413 if (is.na(python))
414 stop("internal error: RENV_PYTHON is not set")
415
416 renv_python_validate(python)
417
418 }
419
420 renv_python_validate <- function(python) {
421
422 if (!file.exists(python)) {
423 fmt <- "python %s does not exist"
424 stopf(fmt, renv_path_pretty(python))
425 }
426
427 invisible(python)
428
429 }