1use std::env;
2use std::fs::read_dir;
3use std::fs::read_to_string;
4use std::io;
5use std::io::ErrorKind;
6use std::path::PathBuf;
7
8fn get_project_root() -> io::Result<PathBuf> {
9 let path = env::current_dir()?;
10 let path_ancestors = path.as_path().ancestors();
11
12 for p in path_ancestors {
13 let has_cargo = read_dir(p)?.any(|p| p.unwrap().file_name() == *"Cargo.lock");
14 if has_cargo {
15 return Ok(PathBuf::from(p));
16 }
17 }
18 Err(io::Error::new(
19 ErrorKind::NotFound,
20 "Ran out of places to find Cargo.toml",
21 ))
22}
23
24pub fn load_input(filename: &str) -> String {
25 let mut path = get_project_root().expect("Cannot get root");
26 path.push("input/");
27 path.push(filename);
28 path.set_extension("txt");
29
30 read_to_string(&path)
31 .unwrap_or_else(|_| panic!("Cannot read input file \"{}\"", path.display()))
32}