From b1e9490f55e4f360c249a107dcc5809a663dec42 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 25 Dec 2021 21:49:16 +0100 Subject: add match meta header to logs --- planetwars-localdev/src/web/mod.rs | 47 +++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 11 deletions(-) (limited to 'planetwars-localdev/src/web/mod.rs') diff --git a/planetwars-localdev/src/web/mod.rs b/planetwars-localdev/src/web/mod.rs index a5d0989..cd94f5e 100644 --- a/planetwars-localdev/src/web/mod.rs +++ b/planetwars-localdev/src/web/mod.rs @@ -11,11 +11,15 @@ use mime_guess; use rust_embed::RustEmbed; use serde::{Deserialize, Serialize}; use std::{ + fs, + io::{self, BufRead}, net::SocketAddr, path::{self, PathBuf}, sync::Arc, }; +use crate::match_runner::MatchMeta; + struct State { project_root: PathBuf, } @@ -47,11 +51,13 @@ pub async fn run(project_root: PathBuf) { } #[derive(Serialize, Deserialize)] -struct Match { +struct MatchData { name: String, + #[serde(flatten)] + meta: MatchMeta, } -async fn list_matches(Extension(state): Extension>) -> Json> { +async fn list_matches(Extension(state): Extension>) -> Json> { let matches = state .project_root .join("matches") @@ -59,29 +65,48 @@ async fn list_matches(Extension(state): Extension>) -> Json>(); Json(matches) } // extracts 'filename' if the entry matches'$filename.log'. -fn extract_match_name(entry: std::fs::DirEntry) -> Option { +fn get_match_data(entry: &fs::DirEntry) -> io::Result { let file_name = entry.file_name(); let path = path::Path::new(&file_name); - if path.extension() == Some("log".as_ref()) { - path.file_stem() - .and_then(|name| name.to_str()) - .map(|name| name.to_string()) - } else { - None + + let name = get_match_name(&path) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid match name"))?; + + let meta = read_match_meta(&entry.path())?; + + Ok(MatchData { name, meta }) +} + +fn get_match_name(path: &path::Path) -> Option { + if path.extension() != Some("log".as_ref()) { + return None; } + + path.file_stem() + .and_then(|name| name.to_str()) + .map(|name| name.to_string()) +} + +fn read_match_meta(path: &path::Path) -> io::Result { + let file = fs::File::open(path)?; + let mut reader = io::BufReader::new(file); + let mut line = String::new(); + reader.read_line(&mut line)?; + let meta: MatchMeta = serde_json::from_str(&line)?; + Ok(meta) } async fn get_match(Extension(state): Extension>, Path(id): Path) -> String { let mut match_path = state.project_root.join("matches").join(id); match_path.set_extension("log"); - std::fs::read_to_string(match_path).unwrap() + fs::read_to_string(match_path).unwrap() } async fn index_handler() -> impl IntoResponse { -- cgit v1.2.3