ctb_formats_python/
python.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use include_dir::{Dir, include_dir};
30use rustpython::{Interpreter, InterpreterBuilder, InterpreterBuilderExt};
31use rustpython_vm::{VirtualMachine, builtins::PyBaseExceptionRef};
32use std::path::Path;
33
34pub mod cli;
35pub use cli::{PythonArgs, run_python_cli};
36
37static PYTHON_DATA_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/data");
38
39pub(crate) fn get_python_data(key: &str) -> Option<Vec<u8>> {
40 get_embedded_asset(&PYTHON_DATA_DIR, key)
41}
42
43pub fn create_interpreter() -> Interpreter {
45 let mut settings = rustpython_vm::Settings::default();
46 settings.stdio_encoding = Some("utf-8".to_string());
47 settings.utf8_mode = 1;
48 InterpreterBuilder::new()
49 .settings(settings)
50 .init_stdlib()
51 .build()
52}
53
54fn py_err_to_anyhow(
56 vm: &VirtualMachine,
57 exc: PyBaseExceptionRef,
58) -> anyhow::Error {
59 let mut buf = String::new();
60 let _ = vm.write_exception(&mut buf, &exc);
61 if buf.is_empty() {
62 anyhow::anyhow!("Python exception occurred")
63 } else {
64 anyhow::anyhow!("{buf}")
65 }
66}
67
68pub fn run_python_code(code: &str) -> Result<()> {
70 let interp = create_interpreter();
71 interp.enter(|vm| {
72 vm.run_simple_string(code)
73 .map_err(|exc| py_err_to_anyhow(vm, exc))?;
74 Ok(())
75 })
76}
77
78pub fn eval_python_expression(expr: &str) -> Result<String> {
80 let interp = create_interpreter();
81 interp.enter(|vm| {
82 let scope = vm.new_scope_with_builtins();
83 let result = vm
84 .run_block_expr(scope, expr)
85 .map_err(|exc| py_err_to_anyhow(vm, exc))?;
86 let repr = result.str(vm).map_err(|exc| py_err_to_anyhow(vm, exc))?;
87 Ok(repr.to_string_lossy().into_owned())
88 })
89}
90
91pub fn run_python_script(script_path: &Path, args: &[&str]) -> Result<()> {
93 let script_str = script_path
94 .to_str()
95 .ok_or_else(|| anyhow::anyhow!("Invalid script path"))?;
96
97 let interp = create_interpreter();
98 interp.enter(|vm| {
99 let scope = vm.new_scope_with_builtins();
100 let mut argv_list = vec![vm.ctx.new_str(script_str).into()];
101 for arg in args {
102 argv_list.push(vm.ctx.new_str(*arg).into());
103 }
104 let sys_argv = vm.ctx.new_list(argv_list);
105 vm.sys_module
106 .set_attr("argv", sys_argv, vm)
107 .map_err(|exc| py_err_to_anyhow(vm, exc))?;
108
109 vm.run_script(scope, script_str)
110 .map_err(|exc| py_err_to_anyhow(vm, exc))?;
111 Ok(())
112 })
113}
114
115#[cfg(test)]
116#[allow(
117 clippy::panic,
118 clippy::expect_used,
119 clippy::unwrap_used,
120 clippy::unwrap_in_result,
121 clippy::panic_in_result_fn,
122 clippy::indexing_slicing,
123 clippy::arithmetic_side_effects,
124 reason = "Standard repository test boilerplate"
125)]
126mod tests {
127 use super::*;
128
129 #[crate::ctb_test]
130 fn test_eval_simple_expression() -> Result<()> {
131 let res = eval_python_expression("2 + 2")?;
132 assert_eq!(res, "4");
133 Ok(())
134 }
135
136 #[crate::ctb_test]
137 fn test_run_python_code_with_imports() -> Result<()> {
138 let handle = std::thread::Builder::new()
139 .name("python-test-thread".to_owned())
140 .stack_size(8 * 1024 * 1024)
141 .spawn(|| {
142 let code = r#"
143import json
144data = json.loads('{"hello": "world"}')
145assert data["hello"] == "world"
146"#;
147 run_python_code(code)
148 })
149 .expect("Failed to spawn thread");
150 handle.join().expect("Thread panicked")
151 }
152
153 #[crate::ctb_test]
154 fn test_python_data_dir() {
155 let data = get_python_data("nonexistent");
156 assert!(data.is_none());
157 }
158
159 #[crate::ctb_test]
160 fn test_python_lzma_module() -> Result<()> {
161 let handle = std::thread::Builder::new()
162 .name("python-lzma-test".to_owned())
163 .stack_size(8 * 1024 * 1024)
164 .spawn(|| {
165 let code = r#"
166import lzma
167data = b"hello world from pure-rust lzma2 in rustpython!"
168
169# Test default XZ container
170compressed_xz = lzma.compress(data)
171decompressed_xz = lzma.decompress(compressed_xz)
172assert decompressed_xz == data
173
174# Test ALONE (.lzma) container
175compressed_alone = lzma.compress(data, format=lzma.FORMAT_ALONE)
176decompressed_alone = lzma.decompress(compressed_alone, format=lzma.FORMAT_ALONE)
177assert decompressed_alone == data
178
179# Test auto-detection on ALONE container
180decompressed_auto = lzma.decompress(compressed_alone)
181assert decompressed_auto == data
182
183assert lzma.is_check_supported(lzma.CHECK_CRC32)
184assert lzma.is_check_supported(lzma.CHECK_CRC64)
185assert lzma.is_check_supported(lzma.CHECK_SHA256)
186"#;
187 run_python_code(code)
188 })
189 .expect("Failed to spawn thread");
190 handle.join().expect("Thread panicked")
191 }
192}