-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpython.rs
More file actions
441 lines (380 loc) · 13.7 KB
/
Copy pathpython.rs
File metadata and controls
441 lines (380 loc) · 13.7 KB
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
use std::path::{Path, PathBuf};
use reqwest::Client;
use tauri::AppHandle;
use tokio::process::Command;
use super::common::install_from_archive_with_progress;
use crate::archive::ArchiveFormat;
use crate::config::{load_config, AppConfig};
use crate::error::{AppError, Result};
use crate::github::fetch_python_releases;
use crate::network_config;
use crate::platform::find_python_asset_for_version;
use crate::utils::net::{ensure_success_status, send_get};
use crate::utils::paths::{get_python_exe_path, get_python_runtime_dir, get_venv_python};
const RUNTIME_PY310: &str = "py310";
const RUNTIME_PY312: &str = "py312";
/// Check whether the unified python component is installed.
/// Python is considered installed only when both 3.10 and 3.12 runtimes exist.
pub(super) fn is_component_installed() -> bool {
is_runtime_installed(RUNTIME_PY310) && is_runtime_installed(RUNTIME_PY312)
}
/// Determine whether a given AstrBot version requires Python 3.10.
/// v4.14.6 and earlier -> 3.10, v4.14.7+ -> 3.12.
fn requires_python310(version: &str) -> bool {
let version = version.strip_prefix('v').unwrap_or(version);
let parts: Vec<u32> = version.split('.').filter_map(|s| s.parse().ok()).collect();
match parts.as_slice() {
[major, minor, patch, ..] => (*major, *minor, *patch) <= (4, 14, 6),
[major, minor] => (*major, *minor) <= (4, 14),
[major] => *major <= 4,
_ => false,
}
}
/// Get the appropriate Python executable for a given AstrBot version.
pub fn get_python_for_version(version: &str) -> Result<PathBuf> {
let runtime = if requires_python310(version) {
RUNTIME_PY310
} else {
RUNTIME_PY312
};
let dir = get_python_runtime_dir(runtime);
let exe = get_python_exe_path(&dir);
if exe.exists() {
Ok(exe)
} else {
Err(AppError::python_not_installed())
}
}
/// Install unified Python component (3.10 + 3.12).
pub(super) async fn install_component(
client: &Client,
app_handle: Option<&AppHandle>,
) -> Result<String> {
if is_component_installed() {
return Ok("Python 已安装".to_string());
}
let installed = install_missing_runtimes(client, app_handle).await?;
if installed.is_empty() {
Ok("Python 已安装".to_string())
} else {
Ok(format!("已安装 Python: {}", installed.join(", ")))
}
}
/// Uninstall unified Python component (3.10 + 3.12).
pub(super) fn uninstall_component() -> Result<String> {
let py310_dir = get_python_runtime_dir(RUNTIME_PY310);
let py312_dir = get_python_runtime_dir(RUNTIME_PY312);
let mut removed = Vec::new();
for dir in [&py310_dir, &py312_dir] {
if dir.exists() {
std::fs::remove_dir_all(dir)
.map_err(|e| AppError::io(format!("Failed to remove Python runtime: {}", e)))?;
removed.push(
dir.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string(),
);
}
}
if removed.is_empty() {
Ok("Python 组件未安装".to_string())
} else {
Ok(format!("已卸载 Python: {}", removed.join(", ")))
}
}
/// Reinstall unified Python component (3.10 + 3.12).
pub(super) async fn reinstall_component(
client: &Client,
app_handle: Option<&AppHandle>,
) -> Result<String> {
let py310_dir = get_python_runtime_dir(RUNTIME_PY310);
let py312_dir = get_python_runtime_dir(RUNTIME_PY312);
if py310_dir.exists() {
std::fs::remove_dir_all(&py310_dir)
.map_err(|e| AppError::io(format!("Failed to clean Python 3.10 runtime: {}", e)))?;
}
if py312_dir.exists() {
std::fs::remove_dir_all(&py312_dir)
.map_err(|e| AppError::io(format!("Failed to clean Python 3.12 runtime: {}", e)))?;
}
let installed = install_missing_runtimes(client, app_handle).await?;
Ok(format!("已重新安装 Python: {}", installed.join(", ")))
}
pub async fn pip_install_requirements(
venv_python: &std::path::Path,
core_path: &std::path::Path,
config: &AppConfig,
) -> Result<()> {
let requirements_path = core_path.join("requirements.txt");
if !requirements_path.exists() {
return Ok(());
}
let requirements_path_arg = requirements_path
.to_str()
.ok_or_else(|| AppError::io("requirements.txt path is not valid UTF-8"))?
.to_string();
let default_index = network_config::default_index(config);
let new_path = crate::component::build_instance_path(venv_python, config.ignore_external_path)?;
let proxy_env_vars = match network_config::proxy_env_vars(config) {
Ok(vars) => vars,
Err(e) => {
log::warn!("Failed to prepare proxy env for pip install: {}", e);
Vec::new()
}
};
let mut cmd = Command::new(venv_python);
cmd.arg("-m")
.arg("pip")
.arg("install")
.arg("-qqq")
.arg("-r")
.arg(&requirements_path_arg)
.arg("-i")
.arg(&default_index)
.env("PATH", new_path)
.env_remove("PYTHONHOME");
crate::utils::proxy::apply_proxy_env(&mut cmd, &proxy_env_vars);
#[cfg(target_os = "windows")]
{
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
cmd.creation_flags(CREATE_NO_WINDOW.0);
}
let output = cmd
.output()
.await
.map_err(|e| AppError::python(format!("Failed to install requirements: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(AppError::python(format!(
"Failed to install requirements: {}",
stderr
)));
}
Ok(())
}
/// Create a virtual environment using the appropriate Python for the version.
pub async fn create_venv(venv_dir: &Path, version: &str) -> Result<()> {
let python_exe = get_python_for_version(version)?;
let venv_dir_arg = venv_dir
.to_str()
.ok_or_else(|| AppError::python(format!("venv path is not valid UTF-8: {:?}", venv_dir)))?
.to_string();
if venv_dir.exists() {
let venv_python = get_venv_python(venv_dir);
if venv_python.exists() {
return Ok(());
}
// Venv directory exists but Python executable is missing or corrupted, remove and recreate.
std::fs::remove_dir_all(venv_dir)
.map_err(|e| AppError::python(format!("Failed to remove corrupted venv: {}", e)))?;
}
let mut cmd = Command::new(&python_exe);
#[cfg(target_os = "windows")]
{
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
cmd.creation_flags(CREATE_NO_WINDOW.0);
}
let output = cmd
.args(["-m", "venv", &venv_dir_arg])
.output()
.await
.map_err(|e| {
log::error!("Failed to create venv: {}", e);
AppError::python(format!("Failed to create venv: {}", e))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(AppError::python(format!(
"Failed to create venv: {}",
stderr
)));
}
log::debug!("Venv created at {:?}", venv_dir);
Ok(())
}
fn is_runtime_installed(runtime: &str) -> bool {
let dir = get_python_runtime_dir(runtime);
let exe = get_python_exe_path(&dir);
exe.exists()
}
async fn install_missing_runtimes(
client: &Client,
app_handle: Option<&AppHandle>,
) -> Result<Vec<String>> {
let mut versions = Vec::new();
if !is_runtime_installed(RUNTIME_PY310) {
let target_dir = get_python_runtime_dir(RUNTIME_PY310);
let version = install_python_version(client, "3.10", &target_dir, app_handle).await?;
versions.push(version);
}
if !is_runtime_installed(RUNTIME_PY312) {
let target_dir = get_python_runtime_dir(RUNTIME_PY312);
let version = install_python_version(client, "3.12", &target_dir, app_handle).await?;
versions.push(version);
}
Ok(versions)
}
/// Download and install a specific Python version to the given directory.
async fn install_python_version(
client: &Client,
major_version: &str,
target_dir: &std::path::Path,
app_handle: Option<&AppHandle>,
) -> Result<String> {
let (url, python_version) = match load_config() {
Ok(config) if network_config::mainland_acceleration(config.as_ref()) => {
let asset_names = fetch_mainland_python_asset_names(client).await?;
let (asset_name, version) =
find_mainland_python_asset_for_version(&asset_names, major_version)?;
let download_url =
network_config::build_mainland_python_asset_download_url(&asset_name);
(download_url, version)
}
Ok(config) => {
let (github_url, python_version) =
find_github_python_asset(client, major_version).await?;
(
network_config::build_github_python_asset_download_url(
config.as_ref(),
&github_url,
),
python_version,
)
}
Err(_) => find_github_python_asset(client, major_version).await?,
};
let archive_path = target_dir.join("python.tar.gz");
install_from_archive_with_progress(
client,
&url,
target_dir,
&archive_path,
ArchiveFormat::TarGz,
"python",
app_handle,
)
.await?;
let python_exe = get_python_exe_path(target_dir);
if !python_exe.exists() {
return Err(AppError::python(format!(
"Python runtime extracted but executable not found: {:?}",
python_exe
)));
}
Ok(python_version)
}
async fn find_github_python_asset(
client: &Client,
major_version: &str,
) -> Result<(String, String)> {
let releases = fetch_python_releases(client).await?;
for release in &releases {
if let Ok((url, version)) = find_python_asset_for_version(&release.assets, major_version) {
return Ok((url, version));
}
}
Err(AppError::python(format!(
"No Python {} build found for current platform",
major_version
)))
}
async fn fetch_mainland_python_asset_names(client: &Client) -> Result<Vec<String>> {
let url = network_config::MAINLAND_PYTHON_BUILD_STANDALONE_BASE;
let resp = send_get(client, url, false)
.await
.map_err(|e| AppError::network(e.to_string()))?;
ensure_success_status(&resp, AppError::network)?;
let body = resp
.text()
.await
.map_err(|e| AppError::network(format!("Failed to read response: {}", e)))?;
let mut asset_names = Vec::new();
for marker in ["href=\"", "href='"] {
let mut rest = body.as_str();
let quote = marker.chars().last().unwrap_or('"');
while let Some(start) = rest.find(marker) {
let fragment = &rest[start + marker.len()..];
let Some(end) = fragment.find(quote) else {
break;
};
push_python_asset_candidate(&mut asset_names, &fragment[..end]);
rest = &fragment[end + 1..];
}
}
if asset_names.is_empty() {
for token in body.split_whitespace() {
push_python_asset_candidate(&mut asset_names, token);
}
}
if asset_names.is_empty() {
return Err(AppError::python("Failed to parse python mirror asset list"));
}
Ok(asset_names)
}
fn push_python_asset_candidate(asset_names: &mut Vec<String>, candidate: &str) {
let trimmed = candidate
.trim()
.trim_matches('"')
.trim_matches('\'')
.trim_matches('/');
if trimmed.is_empty() || trimmed.starts_with('?') || trimmed.starts_with('#') {
return;
}
let Some(name) = trimmed.rsplit('/').next() else {
return;
};
let decoded_name = decode_url_path_segment(name);
if !decoded_name.ends_with(".tar.gz") || asset_names.iter().any(|item| item == &decoded_name) {
return;
}
asset_names.push(decoded_name);
}
fn find_mainland_python_asset_for_version(
asset_names: &[String],
major_version: &str,
) -> Result<(String, String)> {
let arch_target = crate::platform::get_python_arch_target().map_err(AppError::python)?;
let pattern_prefix = format!("cpython-{}", major_version);
let pattern_suffix = format!("{}-install_only_stripped.tar.gz", arch_target);
for asset_name in asset_names {
if asset_name.starts_with(&pattern_prefix) && asset_name.ends_with(&pattern_suffix) {
let version = asset_name
.strip_prefix("cpython-")
.and_then(|s| s.split('+').next())
.unwrap_or(major_version);
return Ok((asset_name.clone(), version.to_string()));
}
}
Err(AppError::python(format!(
"No Python {} asset found in mainland mirror for current platform",
major_version
)))
}
fn decode_url_path_segment(input: &str) -> String {
let bytes = input.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' && index + 2 < bytes.len() {
let hi = hex_value(bytes[index + 1]);
let lo = hex_value(bytes[index + 2]);
if let (Some(hi), Some(lo)) = (hi, lo) {
decoded.push((hi << 4) | lo);
index += 3;
continue;
}
}
decoded.push(bytes[index]);
index += 1;
}
String::from_utf8_lossy(&decoded).into_owned()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}