summaryrefslogtreecommitdiff
path: root/src/files.rs
blob: 7f3daed8552655bd2ec2b955c99da836fb0fbdf9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use json;
use std::io::prelude::*;
use std::fs::File;
use std::path::PathBuf;

use actions::*;

const STATE_FILE: &'static str = "state.json";

const COMMAND_FILE: &'static str = "command.txt";
const PLACE_FILE: &'static str = "place.txt";

pub fn read_file(working_dir: &PathBuf) -> Result<json::JsonValue, String> {
    let state_path = working_dir.join(STATE_FILE);
    let mut file = File::open(state_path.as_path()).map_err(|e| e.to_string())?;
    let mut content = String::new();
    file.read_to_string(&mut content).map_err(|e| e.to_string())?;
    json::parse(content.as_ref()).map_err(|e| e.to_string())
}

pub fn write_action(working_dir: &PathBuf, is_place_phase: bool, action: Action) -> Result<(), String> {
    let filename = if is_place_phase {
        PLACE_FILE
    }
    else {
        COMMAND_FILE
    };
    
    let full_filename = working_dir.join(filename);
    let mut file = File::create(full_filename.as_path()).map_err(|e| e.to_string())?;
    write!(file, "{}", action).map_err(|e| e.to_string())?;

    println!("Making move: {}", action);
    
    Ok(())
}