dancing_droids/src/main.rs
2020-10-28 18:29:16 +01:00

88 lines
2.9 KiB
Rust

// Dancing Droids
// Copyright (C) 2020 Martin HART, Volodymyr PATUTA, Stephane Elias BENABDESLAM
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use clap::{App, Arg};
use std::fs;
use std::io;
mod robot;
mod world;
/// Parse the config file, generate the world and robot pool.
fn parse_config(conf: String, pool: &mut Vec<robot::Robot>) -> Result<world::World, &'static str> {
let mut lines = conf.lines();
// The first line of the config file should be the World.
let raw_line: &str = match lines.next() {
Some(raw) => raw,
None => return Err("Could not read the first line of the config file !"),
};
let mut tokens = raw_line.split_whitespace();
let token1 = match tokens.next() {
Some(raw) => raw,
None => return Err("Could not read the first token of the first line !"),
};
let token2 = match tokens.next() {
Some(raw) => raw,
None => return Err("Could not read the second token of the first line !"),
};
let x: i32 = match token1.parse::<i32>() {
Ok(x) => x,
Err(err) => return Err("Could not convert token one from the first string to i32"),
};
let y: i32 = match token2.parse::<i32>() {
Ok(x) => x,
Err(err) => return Err("Could not convert token two from the first string to i32"),
};
Ok(world::World { x, y })
}
/// Retrieve the content of a file and return it as a string.
fn open_file(filename: &str) -> io::Result<String> {
let content = fs::read_to_string(filename)?;
Ok(content)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// We handle CLI flags here.
let matches = App::new("DancingDroids")
.version("0.1.0")
.about("When droids dance togethers")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.help("Configuration file"),
)
.get_matches();
let raw_conf = open_file(matches.value_of("file").unwrap_or("two_robots.txt"))?;
let mut robot_pool: Vec<robot::Robot> = Vec::new();
let world: world::World = parse_config(raw_conf, &mut robot_pool)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_open_file() {
assert!(open_file("two_robots.txt").is_ok());
assert!(open_file("test_unexisting_file.extension").is_err());
}
}