thag_rs 0.2.0

A versatile cross-platform playground and REPL for Rust snippets, expressions and programs. Accepts a script file or dynamic options.
use clap::Parser;
use std::path::PathBuf;
use std::{
    env,
    fs::{self, File},
    io::Write,
    sync::Once,
};
use thag_proc_macros::safe_println;
use thag_rs::{execute, Cli, DYNAMIC_SUBDIR, TMPDIR};

// Set environment variables before running tests
fn set_up() {
    static INIT: Once = Once::new();
    INIT.call_once(|| unsafe {
        std::env::set_var("TEST_ENV", "1");
        std::env::set_var("VISUAL", "cat");
        std::env::set_var("EDITOR", "cat");
    });
}

#[test]
fn test_script_runner_with_dependencies() -> Result<(), Box<dyn std::error::Error>> {
    set_up();
    // Create a temporary directory for the test project
    let temp_dir: PathBuf = TMPDIR.join(DYNAMIC_SUBDIR);
    fs::create_dir_all(&temp_dir).expect("Failed to create temp_dir directory");
    // Create a sample script file with a dependency
    let source_path = temp_dir.join("script.rs");
    let mut script_file = File::create(&source_path)?;
    let thag_rs_path = env::current_dir()?;
    write!(
        script_file,
        r#"/*[toml]
[dependencies]
thag_rs = {{ path = {thag_rs_path:#?} }}
*/
use thag_rs::{{vprtln, Color}};
use thag_rs::Verbosity;
fn main() {{
    vprtln!(Verbosity::Normal, "Color::light_cyan().bold()={{:#?}}", Color::light_cyan().bold());
}}"#
    )?;

    // Simulate command-line arguments
    let args = vec![
        "thag_rs", // Typically, this would be the binary name
        source_path.to_str().unwrap(),
        "--",
        "2>&1",
    ];

    // Save the real command-line arguments and replace them with the test ones
    let real_args: Vec<String> = env::args().collect();

    unsafe {
        env::set_var("RUST_TEST_ARGS", real_args.join(" "));
    }

    // Set up clap to use the test arguments
    let mut cli = Cli::parse_from(&args);

    safe_println!("cli={:#?}", cli);
    // thag_rs::Cli = cli;

    // Call the execute function directly
    execute(&mut cli)?;

    // Restore the real command-line arguments
    unsafe {
        env::set_var("RUST_TEST_ARGS", real_args.join(" "));
    }

    Ok(())
}

// Include tests to ensure that every single script in the demo directory will
// compile (not run, since we would have to pass many of them different arguments).
// These tests are built by thag_rs/build.rs.
include!(concat!(env!("OUT_DIR"), "/generated_tests.rs"));