|
| 1 | +use miette::miette; |
| 2 | +use std::env; |
| 3 | +use std::fs; |
| 4 | +use std::io::{self, BufRead}; |
| 5 | +use std::os::unix::process::CommandExt; |
| 6 | +use std::path::{Path, PathBuf}; |
| 7 | +use std::process::Command; |
| 8 | + |
| 9 | +fn find_pyvenv_cfg(start_path: &Path) -> Option<PathBuf> { |
| 10 | + let parent = start_path.parent()?.parent()?; |
| 11 | + let cfg_path = parent.join("pyvenv.cfg"); |
| 12 | + if cfg_path.exists() && cfg_path.is_file() { |
| 13 | + Some(cfg_path) |
| 14 | + } else { |
| 15 | + None |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +fn extract_pyvenv_version_info(cfg_path: &Path) -> Result<Option<String>, io::Error> { |
| 20 | + let file = fs::File::open(cfg_path)?; |
| 21 | + let reader = io::BufReader::new(file); |
| 22 | + for line in reader.lines() { |
| 23 | + let line = line?; |
| 24 | + if let Some((key, value)) = line.split_once("=") { |
| 25 | + let key = key.trim(); |
| 26 | + let value = value.trim(); |
| 27 | + if key == "version_info" { |
| 28 | + return Ok(Some(value.to_string())); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + Ok(None) |
| 33 | +} |
| 34 | + |
| 35 | +fn parse_version_info(version_str: &str) -> Option<String> { |
| 36 | + // To avoid pulling in the regex crate, we're gonna do this by hand. |
| 37 | + let parts: Vec<_> = version_str.split(".").collect(); |
| 38 | + match parts[..] { |
| 39 | + [major, minor, ..] => Some(format!("{}.{}", major, minor)), |
| 40 | + _ => None, |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +fn compare_versions(version_from_cfg: &str, executable_path: &Path) -> bool { |
| 45 | + if let Some(file_name) = executable_path.file_name().and_then(|n| n.to_str()) { |
| 46 | + return file_name.ends_with(&format!("python{}", version_from_cfg)); |
| 47 | + } else { |
| 48 | + false |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +fn find_python_executables(version_from_cfg: &str, exclude_dir: &Path) -> Option<Vec<PathBuf>> { |
| 53 | + let python_prefix = format!("python{}", version_from_cfg); |
| 54 | + let path_env = env::var_os("PATH")?; |
| 55 | + |
| 56 | + let binaries: Vec<_> = env::split_paths(&path_env) |
| 57 | + .filter_map(|path_dir| { |
| 58 | + let potential_executable = path_dir.join(&python_prefix); |
| 59 | + if potential_executable.exists() && potential_executable.is_file() { |
| 60 | + Some(potential_executable) |
| 61 | + } else { |
| 62 | + None |
| 63 | + } |
| 64 | + }) |
| 65 | + .filter(|potential_executable| potential_executable.parent() != Some(exclude_dir)) |
| 66 | + .filter(|potential_executable| compare_versions(version_from_cfg, &potential_executable)) |
| 67 | + .collect(); |
| 68 | + |
| 69 | + if binaries.len() > 0 { |
| 70 | + Some(binaries) |
| 71 | + } else { |
| 72 | + None |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +fn main() -> miette::Result<()> { |
| 77 | + let current_exe = env::current_exe().unwrap(); |
| 78 | + let args: Vec<_> = env::args().collect(); |
| 79 | + |
| 80 | + #[cfg(feature = "debug")] |
| 81 | + println!("[aspect] Current executable path: {:?}", current_exe); |
| 82 | + |
| 83 | + let pyvenv_cfg_path = match find_pyvenv_cfg(¤t_exe) { |
| 84 | + Some(path) => { |
| 85 | + #[cfg(feature = "debug")] |
| 86 | + eprintln!("[aspect] Found pyvenv.cfg at: {:?}", path); |
| 87 | + path |
| 88 | + } |
| 89 | + None => { |
| 90 | + return Err(miette!("pyvenv.cfg not found one directory level up.")); |
| 91 | + } |
| 92 | + }; |
| 93 | + |
| 94 | + let version_info_result = extract_pyvenv_version_info(&pyvenv_cfg_path).unwrap(); |
| 95 | + let version_info = match version_info_result { |
| 96 | + Some(v) => { |
| 97 | + #[cfg(feature = "debug")] |
| 98 | + eprintln!("[aspect] version_info from pyvenv.cfg: {}", v); |
| 99 | + v |
| 100 | + } |
| 101 | + None => { |
| 102 | + return Err(miette!("version_info key not found in pyvenv.cfg.")); |
| 103 | + } |
| 104 | + }; |
| 105 | + |
| 106 | + let target_python_version = match parse_version_info(&version_info) { |
| 107 | + Some(v) => { |
| 108 | + #[cfg(feature = "debug")] |
| 109 | + eprintln!("[aspect] Parsed target Python version (major.minor): {}", v); |
| 110 | + v |
| 111 | + } |
| 112 | + None => { |
| 113 | + return Err(miette!("Could not parse version_info as x.y.")); |
| 114 | + } |
| 115 | + }; |
| 116 | + |
| 117 | + let exclude_dir = current_exe.parent().unwrap(); |
| 118 | + if let Some(python_executables) = find_python_executables(&target_python_version, exclude_dir) { |
| 119 | + #[cfg(feature = "debug")] |
| 120 | + { |
| 121 | + eprintln!( |
| 122 | + "[aspect] Found potential Python interpreters in PATH with matching version:" |
| 123 | + ); |
| 124 | + for exe in &python_executables { |
| 125 | + println!("[aspect] - {:?}", exe); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + let interpreter_path = &python_executables[0]; |
| 130 | + let exe_path = current_exe.to_string_lossy().into_owned(); |
| 131 | + let exec_args = &args[1..]; |
| 132 | + |
| 133 | + #[cfg(feature = "debug")] |
| 134 | + eprintln!( |
| 135 | + "[aspect] Attempting to execute: {:?} with argv[0] as {:?} and args as {:?}", |
| 136 | + interpreter_path, exe_path, exec_args, |
| 137 | + ); |
| 138 | + |
| 139 | + let mut cmd = Command::new(interpreter_path); |
| 140 | + cmd.args(exec_args); |
| 141 | + |
| 142 | + // Lie about the value of argv0 to hoodwink the interpreter as to its |
| 143 | + // location on Linux-based platforms. |
| 144 | + if cfg!(target_os = "linux") { |
| 145 | + cmd.arg0(&exe_path); |
| 146 | + } |
| 147 | + |
| 148 | + // On MacOS however, there are facilities for asking the C runtime/OS |
| 149 | + // what the real name of the interpreter executable is, and that value |
| 150 | + // is preferred while argv[0] is ignored. So we need to use a different |
| 151 | + // mechanism to lie to the target interpreter about its own path. |
| 152 | + // |
| 153 | + // https://github.com/python/cpython/blob/68e72cf3a80362d0a2d57ff0c9f02553c378e537/Modules/getpath.c#L778 |
| 154 | + // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONEXECUTABLE |
| 155 | + if cfg!(target_os = "macos") { |
| 156 | + cmd.env("PYTHONEXECUTABLE", exe_path); |
| 157 | + } |
| 158 | + |
| 159 | + let _ = cmd.exec(); |
| 160 | + |
| 161 | + return Ok(()); |
| 162 | + } else { |
| 163 | + return Err(miette!( |
| 164 | + "No suitable Python interpreter found in PATH matching version '{}'.", |
| 165 | + &version_info, |
| 166 | + )); |
| 167 | + } |
| 168 | +} |
0 commit comments