Skip to content

Commit

Permalink
implemented editing coordinates
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderStorm committed Apr 10, 2023
1 parent 815658c commit ad7ab93
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 1 deletion.
File renamed without changes.
File renamed without changes.
80 changes: 79 additions & 1 deletion server/feedback/src/proposed_edits/coordinate.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,93 @@
use crate::proposed_edits::AppliableEdit;
use serde::Deserialize;
use std::path::Path;
use std::ops::Range;
use std::path::{Path, PathBuf};

struct CoordinateFile {
path: PathBuf,
}

impl CoordinateFile {
fn from(path: PathBuf) -> Self {
Self { path }
}
fn matches(&self) -> Range<u32> {
let name = self.path.file_name().unwrap().to_str().unwrap();
match name.split('_').next() {
Some(prefix) => {
let range = prefix
.split('-')
.map(|s| s.parse::<u32>().unwrap())
.collect::<Vec<u32>>();
match range.len() {
1 => range[0]..range[0],
2 => range[0]..range[1],
_ => panic!("Invalid range: {:?}", range),
}
}
None => 0..99999,
}
}
}

#[derive(Deserialize, Clone)]
pub struct Coordinate {
lat: f64,
lon: f64,
}

impl Coordinate {
fn best_matching_file(&self, key: &str, base_dir: &Path) -> PathBuf {
let coord_dir = base_dir.join("data").join("sources").join("coordinate");
let filenames = std::fs::read_dir(coord_dir)
.unwrap()
.map(|res| res.map(|e| e.path()))
.filter_map(|res| res.ok())
.map(CoordinateFile::from);
let best_match = filenames
.filter(|co| co.matches().contains(&key.parse::<u32>().unwrap()))
.min_by_key(|f| {
let Range { start, end } = f.matches();
end - start
})
.expect("No matching file found");
best_match.path
}
}
impl AppliableEdit for Coordinate {
fn apply(&self, key: &str, base_dir: &Path) -> String {
let file = self.best_matching_file(key, base_dir);
let content = std::fs::read_to_string(file.clone()).unwrap();
let mut lines = content.lines().collect::<Vec<&str>>();
let pos_of_line_to_edit = lines
.iter()
.position(|l| l.starts_with(&format!("\"{key}\": ")));
let mut new_line = format!(
"\"{key}\": {{ lat: {lat}, lon: {lon} }}",
lat = self.lat,
lon = self.lon,
);
match pos_of_line_to_edit {
Some(pos) => {
if lines[pos].contains('#') {
new_line += " #";
new_line += lines[pos].split('#').last().unwrap();
}
lines[pos] = &new_line;
}
None => {
//we need to insert a new line at a fitting position
let pos_of_line_to_insert = lines
.iter()
.position(|l| {
let key_at_pos = l.split("\":").next().unwrap().strip_prefix('"').unwrap();
key_at_pos > key
})
.unwrap_or(lines.len());
lines.insert(pos_of_line_to_insert, &new_line)
}
}
std::fs::write(file.as_path(), lines.join("\n")).unwrap();
format!(
"https://nav.tum.de/api/preview_edit/{k}?to_lat={lat}&to_lon={lon}",
k = key,
Expand Down

0 comments on commit ad7ab93

Please sign in to comment.