1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use crate::auditwheel::PlatformTag;
use crate::{BridgeModel, Target};
use anyhow::{bail, format_err, Context, Result};
use regex::Regex;
use serde::Deserialize;
use std::collections::HashSet;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str;
const GET_INTERPRETER_METADATA: &str = include_str!("get_interpreter_metadata.py");
const MINIMUM_PYTHON_MINOR: usize = 6;
const MAXIMUM_PYTHON_MINOR: usize = 12;
const MAXIMUM_PYPY_MINOR: usize = 8;
fn windows_interpreter_no_build(
major: usize,
minor: usize,
target_width: usize,
pointer_width: usize,
min_python_minor: usize,
) -> bool {
if major == 2 {
return true;
}
if major == 3 && minor < min_python_minor {
return true;
}
if pointer_width != target_width {
println!(
"👽 {}.{} is installed as {}-bit, while the target is {}-bit. Skipping.",
major, minor, pointer_width, target_width
);
return true;
}
false
}
fn find_all_windows(target: &Target, min_python_minor: usize) -> Result<Vec<String>> {
let code = "import sys; print(sys.executable or '')";
let mut interpreter = vec![];
let mut versions_found = HashSet::new();
let execution = Command::new("py").arg("-0").output();
if let Ok(output) = execution {
let expr = Regex::new(r" -(\d).(\d)-(\d+)(?: .*)?").unwrap();
let lines = str::from_utf8(&output.stdout).unwrap().lines();
for line in lines {
if let Some(capture) = expr.captures(line) {
let context = "Expected a digit";
let major = capture
.get(1)
.unwrap()
.as_str()
.parse::<usize>()
.context(context)?;
let minor = capture
.get(2)
.unwrap()
.as_str()
.parse::<usize>()
.context(context)?;
if !versions_found.contains(&(major, minor)) {
let pointer_width = capture
.get(3)
.unwrap()
.as_str()
.parse::<usize>()
.context(context)?;
if windows_interpreter_no_build(
major,
minor,
target.pointer_width(),
pointer_width,
min_python_minor,
) {
continue;
}
let version = format!("-{}.{}-{}", major, minor, pointer_width);
let output = Command::new("py")
.args(&[&version, "-c", code])
.output()
.unwrap();
let path = str::from_utf8(&output.stdout).unwrap().trim();
if !output.status.success() || path.trim().is_empty() {
bail!("Couldn't determine the path to python for `py {}`", version);
}
interpreter.push(path.to_string());
versions_found.insert((major, minor));
}
}
}
}
let conda_info = Command::new("conda").arg("info").arg("-e").output();
if let Ok(output) = conda_info {
let lines = str::from_utf8(&output.stdout).unwrap().lines();
let re = Regex::new(r"^([^#].*?)[\s*]+([\w\\:.-]+)\s*$").unwrap();
let mut paths = vec![];
for i in lines {
if let Some(capture) = re.captures(i) {
if &capture[1] == "base" {
continue;
}
paths.push(String::from(&capture[2]));
}
}
for path in paths {
let executable = Path::new(&path).join("python");
let python_info = Command::new(&executable)
.arg("-c")
.arg("import sys; print(sys.version)")
.output();
let python_info = match python_info {
Ok(python_info) => python_info,
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
continue;
} else {
bail!(
"Error getting Python version info from conda env at {}",
path
);
}
}
};
let version_info = str::from_utf8(&python_info.stdout).unwrap();
let expr = Regex::new(r"(\d).(\d).(\d+)").unwrap();
if let Some(capture) = expr.captures(version_info) {
let major = capture.get(1).unwrap().as_str().parse::<usize>().unwrap();
let minor = capture.get(2).unwrap().as_str().parse::<usize>().unwrap();
if !versions_found.contains(&(major, minor)) {
let pointer_width = if version_info.contains("64 bit (AMD64)") {
64_usize
} else {
32_usize
};
if windows_interpreter_no_build(
major,
minor,
target.pointer_width(),
pointer_width,
min_python_minor,
) {
continue;
}
interpreter.push(String::from(executable.to_str().unwrap()));
versions_found.insert((major, minor));
}
}
}
}
if interpreter.is_empty() {
bail!(
"Could not find any interpreters, are you sure you have python installed on your PATH?"
);
};
Ok(interpreter)
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum InterpreterKind {
CPython,
PyPy,
}
impl fmt::Display for InterpreterKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InterpreterKind::CPython => write!(f, "CPython"),
InterpreterKind::PyPy => write!(f, "PyPy"),
}
}
}
#[derive(Deserialize)]
struct IntepreterMetadataMessage {
major: usize,
minor: usize,
abiflags: Option<String>,
interpreter: String,
ext_suffix: Option<String>,
platform: String,
abi_tag: Option<String>,
base_prefix: String,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PythonInterpreter {
pub major: usize,
pub minor: usize,
pub abiflags: String,
pub target: Target,
pub executable: PathBuf,
pub ext_suffix: String,
pub interpreter_kind: InterpreterKind,
pub abi_tag: Option<String>,
pub libs_dir: PathBuf,
}
fn fun_with_abiflags(
message: &IntepreterMetadataMessage,
target: &Target,
bridge: &BridgeModel,
) -> Result<String> {
if bridge != &BridgeModel::Cffi && target.get_python_os() != message.platform {
bail!(
"sys.platform in python, {}, and the rust target, {:?}, don't match ಠ_ಠ",
message.platform,
target,
)
}
if message.major != 3 || message.minor < 5 {
bail!(
"Only python >= 3.5 is supported, while you're using python {}.{}",
message.major,
message.minor
);
}
if message.interpreter == "pypy" {
Ok("".to_string())
} else if message.platform == "windows" {
if message.abiflags.is_some() {
bail!("A python 3 interpreter on windows does not define abiflags in its sysconfig ಠ_ಠ")
} else {
Ok("".to_string())
}
} else if let Some(ref abiflags) = message.abiflags {
if message.minor >= 8 {
Ok(abiflags.to_string())
} else if (abiflags != "m") && (abiflags != "dm") {
bail!("A python 3 interpreter on linux or mac os must have 'm' or 'dm' as abiflags ಠ_ಠ")
} else {
Ok(abiflags.to_string())
}
} else {
bail!("A python 3 interpreter on linux or mac os must define abiflags in its sysconfig ಠ_ಠ")
}
}
impl PythonInterpreter {
pub fn get_tag(&self, platform_tag: PlatformTag, universal2: bool) -> String {
match self.interpreter_kind {
InterpreterKind::CPython => {
let platform = self.target.get_platform_tag(platform_tag, universal2);
if self.target.is_unix() {
format!(
"cp{major}{minor}-cp{major}{minor}{abiflags}-{platform}",
major = self.major,
minor = self.minor,
abiflags = self.abiflags,
platform = platform
)
} else {
format!(
"cp{major}{minor}-none-{platform}",
major = self.major,
minor = self.minor,
platform = platform
)
}
}
InterpreterKind::PyPy => {
let platform = self.target.get_platform_tag(platform_tag, universal2);
format!(
"pp{major}{minor}-pypy{major}{minor}_{abi_tag}-{platform}",
major = self.major,
minor = self.minor,
abi_tag = self
.abi_tag
.clone()
.expect("PyPy's syconfig didn't define an `SOABI` ಠ_ಠ"),
platform = platform,
)
}
}
}
pub fn get_library_name(&self, base: &str) -> String {
format!(
"{base}{ext_suffix}",
base = base,
ext_suffix = self.ext_suffix
)
}
pub fn check_executable(
executable: impl AsRef<Path>,
target: &Target,
bridge: &BridgeModel,
) -> Result<Option<PythonInterpreter>> {
let output = Command::new(&executable.as_ref())
.args(&["-c", GET_INTERPRETER_METADATA])
.output();
let err_msg = format!(
"Trying to get metadata from the python interpreter '{}' failed",
executable.as_ref().display()
);
let output = match output {
Ok(output) => {
if output.status.success() {
output
} else {
let stderr = str::from_utf8(&output.stderr).unwrap();
if stderr.starts_with(&format!(
"pyenv: {}: command not found",
executable.as_ref().display()
)) {
eprintln!(
"⚠️ Warning: skipped unavailable python interpreter '{}' from pyenv",
executable.as_ref().display()
);
return Ok(None);
} else {
eprintln!("{}", stderr);
bail!(err_msg);
}
}
}
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
return Ok(None);
} else {
return Err(err).context(err_msg);
}
}
};
let message: IntepreterMetadataMessage = serde_json::from_slice(&output.stdout)
.context(err_msg)
.context(String::from_utf8_lossy(&output.stdout).trim().to_string())?;
if (message.major == 2 && message.minor != 7) || (message.major == 3 && message.minor < 5) {
return Ok(None);
}
let interpreter;
match message.interpreter.as_str() {
"cpython" => interpreter = InterpreterKind::CPython,
"pypy" => interpreter = InterpreterKind::PyPy,
_ => {
bail!("Invalid interpreter");
}
};
let abiflags = fun_with_abiflags(&message, target, bridge).context(format_err!(
"Failed to get information from the python interpreter at {}",
executable.as_ref().display()
))?;
Ok(Some(PythonInterpreter {
major: message.major,
minor: message.minor,
abiflags,
target: target.clone(),
executable: executable.as_ref().to_path_buf(),
ext_suffix: message
.ext_suffix
.context("syconfig didn't define an `EXT_SUFFIX` ಠ_ಠ")?,
interpreter_kind: interpreter,
abi_tag: message.abi_tag,
libs_dir: PathBuf::from(message.base_prefix).join("libs"),
}))
}
pub fn find_all(
target: &Target,
bridge: &BridgeModel,
min_python_minor: Option<usize>,
) -> Result<Vec<PythonInterpreter>> {
let min_python_minor = min_python_minor.unwrap_or(MINIMUM_PYTHON_MINOR);
let executables = if target.is_windows() {
find_all_windows(target, min_python_minor)?
} else {
let mut executables: Vec<String> = (min_python_minor..MAXIMUM_PYTHON_MINOR)
.map(|minor| format!("python3.{}", minor))
.collect();
if matches!(bridge, BridgeModel::Cffi) || bridge.is_bindings("pyo3") {
executables.extend(
(min_python_minor..MAXIMUM_PYPY_MINOR).map(|minor| format!("pypy3.{}", minor)),
);
}
executables
};
let mut available_versions = Vec::new();
for executable in executables {
if let Some(version) = PythonInterpreter::check_executable(&executable, target, bridge)?
{
available_versions.push(version);
}
}
Ok(available_versions)
}
pub fn check_executables(
executables: &[PathBuf],
target: &Target,
bridge: &BridgeModel,
) -> Result<Vec<PythonInterpreter>> {
let mut available_versions = Vec::new();
for executable in executables {
if let Some(version) = PythonInterpreter::check_executable(executable, target, bridge)
.context(format!(
"{} is not a valid python interpreter",
executable.display()
))? {
available_versions.push(version);
} else {
bail!(
"Python interpreter `{}` doesn't exist",
executable.display()
);
}
}
Ok(available_versions)
}
}
impl fmt::Display for PythonInterpreter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {}.{}{} at {}",
self.interpreter_kind,
self.major,
self.minor,
self.abiflags,
self.executable.display()
)
}
}