conversation/
conversation.rs

1use console_prompt::{Command, command_loop, DynamicContext};
2use std::error::Error;
3
4fn change(_args: &[&str], context: &mut DynamicContext)->Result<String, Box<dyn Error>>{
5    match context.get_mut::<String>("name") {
6        Some(mut_ref) => {
7            *mut_ref = _args[0].to_string();
8            return Ok(format!("you changed their name to {}", *mut_ref));
9        },
10        None => return Ok("you are not in a conversation with a person".to_string()),
11    }
12}
13
14fn hello(_args: &[&str], context: &mut DynamicContext)->Result<String, Box<dyn Error>>{
15    match context.get::<String>("name") {
16        None => { 
17            return Ok("you are not in a conversation with a person".to_string()) 
18        },
19        Some(name ) => {
20            return Ok(format!("You said hello to {name} I guess"));
21        }
22    }
23}
24
25// test function that demonstrates calling a command_loop sub call
26// to provide a nested state
27fn converse(args: &[&str], _context: &mut DynamicContext)->Result<String, Box<dyn Error>>{
28    if args.len() == 0 {
29        return Ok("no name provided".to_string());
30    }
31    println!("interacting with: {}", args[0]);
32    let commands = vec![
33        Command{command: "hello", func: hello, help_output: "hello - say hello"},
34        Command{command: "change", func: change, help_output: "change <name> - change the name of the person with whom you're speaking"},
35    ];
36
37    // let mut name: Option<Box<dyn Any>> = Some(Box::new(args[0].to_string()));
38    let mut context = DynamicContext::new();
39    context.set("name",args[0].to_string());
40    // passing the arguments for the converse commands as context
41    // to the commands in the next command loop for reference
42    if let Err(e) = command_loop(&commands, &mut context){
43        eprintln!("error running interact command loop: {}", e);
44    }
45    Ok(String::new())
46}
47
48fn main(){
49    let commands = vec![
50        Command{
51            command: "converse",
52            func: converse,
53            help_output: "converse <name> - interact with a person"
54        },
55    ];
56
57    // start the command loop with the provided commands
58    if let Err(e) = command_loop(&commands, &mut DynamicContext::new()){
59        eprintln!("error running command loop: {}", e.to_string());
60    }
61}