jimtcl 0.4.0-beta5

Embed Jim Tcl in Rust.
Documentation
//! Command-line shells.

use clap::Parser;

use crate::{Interp, JimObject, JimResult};
use crate::{JimError, sys};

/// Rust wrapper to implement jimsh
#[derive(Parser, Debug)]
#[command(version)]
pub struct Jimsh {
    /// Tcl script to execute, optionally with arguments.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    pub script: Vec<String>,
}

impl Jimsh {
    /// Get the script file to run.
    pub fn script_file(&self) -> Option<&str> {
        self.script.first().map(String::as_str)
    }

    /// Get the arguments to be passed to the script.
    pub fn script_args(&self) -> &[String] {
        if self.script.len() > 0 {
            &self.script[1..]
        } else {
            &self.script
        }
    }

    /// Set up an interpreter environment to run the script.
    pub fn setup_env(&self, interp: &Interp) -> JimResult<()> {
        interp.eval_source("initjimsh.tcl", 1, sys::tclexts::initjimsh)?;
        if let Some(path) = self.script_file() {
            interp.set_variable("argv0", path)?;
        }
        let argv = JimObject::empty(interp);
        for arg in self.script_args() {
            argv.list_append(arg.as_str());
        }
        interp.set_variable("argv", argv)?;
        Ok(())
    }

    /// Run the command line in the specified interpreter.  Returns the Jim
    /// exit code on success.
    ///
    /// **Note:** you must call [setup_env] before this function to properly
    /// initialize the interpreter variables. The calls are not automatically
    /// linked, to allow embedding code to perform additional post-setup
    /// actions.
    pub fn run(&self, interp: &Interp) -> JimResult<i32> {
        let result = if let Some(path) = self.script_file() {
            interp.eval_file(path)
        } else {
            interp.interactive_prompt()
        };

        // special-case unhandled errors to get stacktrace
        if let Err(JimError::Error(msg)) = &result {
            eprintln!("Tcl script failed: {}", msg);
            let stack = interp.stack_trace();
            let obj = interp.new_string("stackdump");
            obj.list_append(stack);
            let result = interp.eval_object(&obj)?;
            eprintln!("{}", result);
            Ok(1)
        } else {
            interp.resolve_exit(result)
        }
    }
}