ctb_formats_python/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! CLI entrypoint for embedded Python interpreter.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::Result;
30use rustpython::{InterpreterBuilder, InterpreterBuilderExt};
31use std::io::{IsTerminal, Read};
32use std::path::Path;
33
34/// Command line arguments for embedded Python interpreter.
35#[derive(clap::Args, Debug, Clone, Default)]
36pub struct PythonArgs {
37    /// Program passed in as string (terminates option list)
38    #[arg(short = 'c')]
39    pub command: Option<String>,
40
41    /// Run library module as a script (terminates option list)
42    #[arg(short = 'm')]
43    pub module: Option<String>,
44
45    /// Don't write .pyc files on import
46    #[arg(short = 'B')]
47    pub dont_write_bytecode: bool,
48
49    /// Force the stdout and stderr streams to be unbuffered
50    #[arg(short = 'u')]
51    pub unbuffered: bool,
52
53    /// Inspect interactively after running script
54    #[arg(short = 'i')]
55    pub inspect: bool,
56
57    /// Isolate Python from the user's environment
58    #[arg(short = 'I')]
59    pub isolate: bool,
60
61    /// Ignore PYTHON* environment variables
62    #[arg(short = 'E')]
63    pub ignore_environment: bool,
64
65    /// Don't print version and copyright messages on interactive startup
66    #[arg(short = 'q')]
67    pub quiet: bool,
68
69    /// Don't add user site directory to sys.path
70    #[arg(short = 's')]
71    pub no_user_site: bool,
72
73    /// Don't imply 'import site' on initialization
74    #[arg(short = 'S')]
75    pub no_site: bool,
76
77    /// Verbose (trace import statements)
78    #[arg(short = 'v', action = clap::ArgAction::Count)]
79    pub verbose: u8,
80
81    /// Python script file, or '-' to read from stdin
82    #[arg(value_name = "SCRIPT")]
83    pub script: Option<String>,
84
85    /// Arguments passed to the Python program in sys.argv[1:]
86    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
87    pub args: Vec<String>,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91enum PythonRunMode {
92    Command(String),
93    Module(String),
94    Script(String),
95    Repl,
96}
97
98fn determine_run_mode(args: &PythonArgs) -> (PythonRunMode, Vec<String>) {
99    if let Some(cmd) = &args.command {
100        let mut argv = vec!["-c".to_string()];
101        if let Some(first_arg) = &args.script {
102            argv.push(first_arg.clone());
103        }
104        argv.extend(args.args.clone());
105        (PythonRunMode::Command(cmd.clone()), argv)
106    } else if let Some(module) = &args.module {
107        let mut argv = vec![module.clone()];
108        if let Some(first_arg) = &args.script {
109            argv.push(first_arg.clone());
110        }
111        argv.extend(args.args.clone());
112        (PythonRunMode::Module(module.clone()), argv)
113    } else if let Some(script) = &args.script {
114        let mut argv = vec![script.clone()];
115        argv.extend(args.args.clone());
116        (PythonRunMode::Script(script.clone()), argv)
117    } else {
118        let mut argv = vec![String::new()];
119        argv.extend(args.args.clone());
120        (PythonRunMode::Repl, argv)
121    }
122}
123
124fn run_python_inner(args: PythonArgs) -> Result<i32> {
125    let (run_mode, argv) = determine_run_mode(&args);
126
127    let mut settings = rustpython_vm::Settings::default();
128    settings.stdio_encoding = Some("utf-8".to_string());
129    settings.utf8_mode = 1;
130    if args.dont_write_bytecode {
131        settings.write_bytecode = false;
132    }
133    if args.unbuffered {
134        settings.buffered_stdio = false;
135    }
136    if args.inspect {
137        settings.inspect = true;
138    }
139    if args.isolate {
140        settings.isolated = true;
141        settings.ignore_environment = true;
142        settings.user_site_directory = false;
143        settings.safe_path = true;
144    }
145    if args.ignore_environment {
146        settings.ignore_environment = true;
147    }
148    if args.quiet {
149        settings.quiet = true;
150    }
151    if args.no_user_site {
152        settings.user_site_directory = false;
153    }
154    if args.no_site {
155        settings.import_site = false;
156    }
157    if args.verbose > 0 {
158        settings.verbose = args.verbose;
159    }
160    if !settings.ignore_environment {
161        for env_var in ["RUSTPYTHONPATH", "PYTHONPATH"] {
162            if let Some(paths) = std::env::var_os(env_var) {
163                if !paths.is_empty() {
164                    for path in std::env::split_paths(&paths) {
165                        if let Ok(s) = path.into_os_string().into_string() {
166                            settings.path_list.push(s);
167                        }
168                    }
169                }
170            }
171        }
172    }
173    settings.argv = argv;
174
175    let builder = InterpreterBuilder::new().settings(settings).init_stdlib();
176    let interp = builder.build();
177
178    let exit_code = interp.run(move |vm| {
179        let scope = vm.new_scope_with_main()?;
180
181        if vm.import("warnings", 0).is_err() {
182            warn!("Failed to import warnings module");
183        }
184
185        if vm.state.config.settings.import_site {
186            let site_result = vm.import("site", 0);
187            if site_result.is_err() {
188                warn!(
189                    "Failed to import site, consider adding the Lib directory to your RUSTPYTHONPATH environment variable"
190                );
191            }
192        }
193
194        match &run_mode {
195            PythonRunMode::Command(command) => {
196                if !vm.state.config.settings.safe_path {
197                    vm.insert_sys_path(vm.new_pyobj(""))?;
198                }
199                vm.run_string(scope.clone(), command, "<string>".to_owned())
200                    .map(drop)?;
201            }
202            PythonRunMode::Module(module) => {
203                if !vm.state.config.settings.safe_path {
204                    // Reason for fallback: module execution mode prepends current working directory to sys.path, falling back to empty string if directory cannot be determined or is non-UTF-8
205                    let cwd = std::env::current_dir()
206                        .ok()
207                        .and_then(|p| p.to_str().map(std::borrow::ToOwned::to_owned))
208                        .unwrap_or_default();
209                    vm.insert_sys_path(vm.new_pyobj(cwd))?;
210                }
211                vm.run_module(module)?;
212            }
213            PythonRunMode::Script(path) => {
214                if path == "-" {
215                    if !vm.state.config.settings.safe_path {
216                        vm.insert_sys_path(vm.new_pyobj(""))?;
217                    }
218                    let mut source = String::new();
219                    std::io::stdin()
220                        .read_to_string(&mut source)
221                        .map_err(|err| vm.new_os_error(err.to_string()))?;
222                    vm.run_string(scope.clone(), &source, "<stdin>".to_owned())
223                        .map(drop)?;
224                } else {
225                    if !vm.state.config.settings.safe_path {
226                        // Reason for fallback: script execution prepends the script directory to sys.path, falling back to empty string when script has no parent directory or is non-UTF-8
227                        let dir = Path::new(path)
228                            .parent()
229                            .and_then(|p| p.to_str())
230                            .unwrap_or("");
231                        vm.insert_sys_path(vm.new_pyobj(dir))?;
232                    }
233                    vm.run_script(scope.clone(), path)?;
234                }
235            }
236            PythonRunMode::Repl => {
237                if !vm.state.config.settings.safe_path {
238                    vm.insert_sys_path(vm.new_pyobj(""))?;
239                }
240                if std::io::stdin().is_terminal() {
241                    rustpython::run_shell(vm, scope.clone())?;
242                } else {
243                    let mut source = String::new();
244                    std::io::stdin()
245                        .read_to_string(&mut source)
246                        .map_err(|err| vm.new_os_error(err.to_string()))?;
247                    vm.run_string(scope.clone(), &source, "<stdin>".to_owned())
248                        .map(drop)?;
249                }
250            }
251        }
252
253        if vm.state.config.settings.inspect {
254            rustpython::run_shell(vm, scope)?;
255        }
256
257        Ok(())
258    });
259
260    // Reason for fallback: exit code from Python VM exceeding i32 range defaults to exit status 1
261    let code = i32::try_from(exit_code).unwrap_or(1);
262    Ok(code)
263}
264
265/// Runs the Python CLI entrypoint with the supplied arguments.
266pub fn run_python_cli(args: &PythonArgs) -> Result<ToolResult> {
267    let args = args.clone();
268    let handle = std::thread::Builder::new()
269        .name("python-cli".to_owned())
270        .stack_size(16 * 1024 * 1024)
271        .spawn(move || run_python_inner(args))?;
272    let exit_code = handle
273        .join()
274        .map_err(|_| anyhow::anyhow!("Python execution thread panicked"))??;
275    Ok(ToolResult::Immediate {
276        stdout: Vec::new(),
277        stderr: Vec::new(),
278        exit_code,
279    })
280}
281
282#[cfg(test)]
283#[allow(
284    clippy::panic,
285    clippy::expect_used,
286    clippy::unwrap_used,
287    clippy::unwrap_in_result,
288    clippy::panic_in_result_fn,
289    clippy::indexing_slicing,
290    clippy::arithmetic_side_effects,
291    reason = "Standard repository test boilerplate"
292)]
293mod tests {
294    use super::*;
295
296    #[crate::ctb_test]
297    fn test_python_cli_command_success() -> Result<()> {
298        let args = PythonArgs {
299            command: Some("import sys; assert 1 + 1 == 2".to_string()),
300            ..Default::default()
301        };
302        let res = run_python_cli(&args)?;
303        match res {
304            ToolResult::Immediate { exit_code, .. } => {
305                assert_eq!(exit_code, 0);
306            }
307            _ => panic!("Expected immediate result"),
308        }
309        Ok(())
310    }
311
312    #[crate::ctb_test]
313    fn test_python_cli_command_system_exit() -> Result<()> {
314        let args = PythonArgs {
315            command: Some("import sys; sys.exit(7)".to_string()),
316            ..Default::default()
317        };
318        let res = run_python_cli(&args)?;
319        match res {
320            ToolResult::Immediate { exit_code, .. } => {
321                assert_eq!(exit_code, 7);
322            }
323            _ => panic!("Expected immediate result"),
324        }
325        Ok(())
326    }
327
328    #[crate::ctb_test]
329    fn test_python_cli_script_execution() -> Result<()> {
330        let script_path = std::env::temp_dir()
331            .join(format!("test_python_cli_{}.py", std::process::id()));
332        std::fs::write(
333            &script_path,
334            r#"
335import os
336import sys
337
338assert os.path.isabs(sys.argv[0]) or len(sys.argv[0]) > 0
339assert sys.argv[1] == "hello"
340assert sys.argv[2] == "--world"
341"#,
342        )?;
343
344        let args = PythonArgs {
345            script: Some(script_path.to_str().unwrap().to_string()),
346            args: vec!["hello".to_string(), "--world".to_string()],
347            ..Default::default()
348        };
349        let res = run_python_cli(&args);
350        let _ = std::fs::remove_file(&script_path);
351        let res = res?;
352        match res {
353            ToolResult::Immediate { exit_code, .. } => {
354                assert_eq!(exit_code, 0);
355            }
356            _ => panic!("Expected immediate result"),
357        }
358        Ok(())
359    }
360
361    #[crate::ctb_test]
362    fn test_python_cli_command_with_argv() -> Result<()> {
363        let args = PythonArgs {
364            command: Some(
365                "import sys; assert sys.argv == ['-c', 'arg1', 'arg2']"
366                    .to_string(),
367            ),
368            script: Some("arg1".to_string()),
369            args: vec!["arg2".to_string()],
370            ..Default::default()
371        };
372        let res = run_python_cli(&args)?;
373        match res {
374            ToolResult::Immediate { exit_code, .. } => {
375                assert_eq!(exit_code, 0);
376            }
377            _ => panic!("Expected immediate result"),
378        }
379        Ok(())
380    }
381
382    #[crate::ctb_test]
383    fn test_python_cli_sysroot_modules() -> Result<()> {
384        let args = PythonArgs {
385            command: Some("import os, sys, subprocess, re, shutil; assert hasattr(shutil, 'copytree')".to_string()),
386            ..Default::default()
387        };
388        let res = run_python_cli(&args)?;
389        match res {
390            ToolResult::Immediate { exit_code, .. } => {
391                assert_eq!(exit_code, 0);
392            }
393            _ => panic!("Expected immediate result"),
394        }
395        Ok(())
396    }
397
398    #[crate::ctb_test]
399    fn test_python_cli_flags_ignore_environment() -> Result<()> {
400        let args = PythonArgs {
401            command: Some(
402                "import sys; assert sys.flags.ignore_environment == 1"
403                    .to_string(),
404            ),
405            ignore_environment: true,
406            ..Default::default()
407        };
408        let res = run_python_cli(&args)?;
409        match res {
410            ToolResult::Immediate { exit_code, .. } => {
411                assert_eq!(exit_code, 0);
412            }
413            _ => panic!("Expected immediate result"),
414        }
415        Ok(())
416    }
417
418    #[crate::ctb_test]
419    fn test_python_cli_flags_isolate() -> Result<()> {
420        let args = PythonArgs {
421            command: Some(
422                "import sys; assert sys.flags.isolated == 1 and sys.flags.ignore_environment == 1 and sys.flags.no_user_site == 1 and sys.flags.safe_path == 1 and '' not in sys.path"
423                    .to_string(),
424            ),
425            isolate: true,
426            ..Default::default()
427        };
428        let res = run_python_cli(&args)?;
429        match res {
430            ToolResult::Immediate { exit_code, .. } => {
431                assert_eq!(exit_code, 0);
432            }
433            _ => panic!("Expected immediate result"),
434        }
435        Ok(())
436    }
437}