Browse Source

Add macro list functionality

master
Graham Littlewood 4 years ago
parent
commit
c8d91e4507
1 changed files with 34 additions and 9 deletions
  1. +34
    -9
      src/commands/cmd_macro.rs

+ 34
- 9
src/commands/cmd_macro.rs View File

@@ -49,6 +49,8 @@ impl Command for CmdMacro {
} else {
response.push("Macro does not exist.");
}
} else if op.as_str().to_string().to_lowercase() == "list"{
response.push(self.list(&id));
} else {
response.push(self.get(&id, &op.as_str().to_string()));
}
@@ -74,15 +76,13 @@ impl Command for CmdMacro {
impl CmdMacro {
pub fn new() -> CmdMacro{
// load macro map from JSON
let mut file = File::open(MACRO_PATH);
match file {
Err(why) => {
file = File::create(MACRO_PATH);
println!("Creating file (error {:?})", why);
},
_ => (),
}
let reader = BufReader::new(file.unwrap());
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(MACRO_PATH)
.unwrap();
let reader = BufReader::new(file);
let macros: HashMap<u64, HashMap<String, String>> = serde_json::from_reader(reader).unwrap_or(HashMap::<u64, HashMap<String, String>>::new());
return CmdMacro {
format:
@@ -149,11 +149,36 @@ impl CmdMacro {
return "Invalid macro".to_string();
}

fn list(&mut self, id: &u64) -> String {
let map: &HashMap<String, String>;
match self.macros.get_mut(id) {
Some(m) => map = m,
None => {
self.macros.insert(*id, HashMap::new());
map = self.macros.get(id).unwrap();
},
}
let mut resp = "Available macros:\n`".to_owned();
for k in map.keys() {
resp += k;
resp += ", ";
}
if resp == "Available macros:\n`" {
resp += "(None)`";
} else {
resp = resp[0..resp.chars().count()-2].to_string()+"`";
}
return resp.to_string();
}

fn save_json(&self) {
let file = OpenOptions::new()
.write(true)
.append(false)
.truncate(true)
.open(MACRO_PATH)
.unwrap();
file.sync_all();
//let writer = BufWriter::new(file.unwrap());
match serde_json::to_writer_pretty(file, &self.macros) {
Err(why) => println!("Macro saving failed ({:?})", why),