use std::process::Command;
use std::path::PathBuf;
use std::io::Write;
#[ must_use ]
pub fn project_dir() -> PathBuf
{
PathBuf::from( env!( "CARGO_MANIFEST_DIR" ) )
}
#[ must_use ]
pub fn repl_command( script : &str ) -> Command
{
let mut cmd = if cfg!( windows )
{
let temp_dir = std::env::temp_dir();
let script_file = temp_dir.join( format!( "genfile_test_{}.txt", std::process::id() ) );
let mut file = std::fs::File::create( &script_file )
.expect( "Should create temp script file" );
file.write_all( script.as_bytes() )
.expect( "Should write script to temp file" );
drop( file );
let mut c = Command::new( "cmd" );
c.arg( "/C" );
c.arg( format!( "cargo run --quiet < {} 2>&1", script_file.display() ) );
c
}
else
{
let mut c = Command::new( "sh" );
c.arg( "-c" );
c.arg( format!( "echo '{script}' | cargo run --quiet 2>&1" ) );
c
};
cmd.current_dir( project_dir() );
cmd
}
#[ must_use ]
pub fn cargo_run_command( args : &[ &str ] ) -> Command
{
let mut cmd = Command::new( "cargo" );
cmd.arg( "run" )
.arg( "--quiet" )
.arg( "--" )
.args( args )
.current_dir( project_dir() );
cmd
}
#[ cfg( test ) ]
mod tests
{
use super::*;
#[ test ]
fn project_dir_exists()
{
let dir = project_dir();
assert!( dir.exists(), "Project directory should exist" );
assert!( dir.is_dir(), "Project directory should be a directory" );
let cargo_toml = dir.join( "Cargo.toml" );
assert!( cargo_toml.exists(), "Cargo.toml should exist in project directory" );
}
#[ test ]
fn cargo_run_command_is_configured()
{
let cmd = cargo_run_command( &[ ".help" ] );
assert_eq!( cmd.get_program(), "cargo" );
}
#[ test ]
fn repl_command_is_configured()
{
let cmd = repl_command( ".help\nexit" );
if cfg!( windows )
{
assert_eq!( cmd.get_program(), "cmd" );
}
else
{
assert_eq!( cmd.get_program(), "sh" );
}
}
}