@@ -4,14 +4,25 @@ use std::error::Error;
44use std:: fs:: { create_dir_all, read_to_string, File } ;
55use std:: io:: Write ;
66use std:: io:: { stdin, stdout} ;
7- use std:: path:: PathBuf ;
7+ use std:: path:: { Path , PathBuf } ;
88use std:: time:: Instant ;
99
1010use crate :: utils:: Line ;
1111
1212const BASE_URL : & str = "https://adventofcode.com" ;
13- const INPUT_DIR : & str = "input" ;
14- const CONN_TOKEN_FILE : & str = ".token" ;
13+
14+ fn input_path ( year : u16 , day : u8 ) -> PathBuf {
15+ format ! ( "input/{}/day{}.txt" , year, day) . into ( )
16+ }
17+
18+ fn token_path ( ) -> PathBuf {
19+ dirs:: config_dir ( )
20+ . map ( |mut cfg| {
21+ cfg. push ( "aoc/token.txt" ) ;
22+ cfg
23+ } )
24+ . unwrap_or_else ( || ".token" . into ( ) )
25+ }
1526
1627pub fn get_input ( year : u16 , day : u8 ) -> Result < String , Box < dyn Error > > {
1728 let mut result = get_from_path_or_else ( & input_path ( year, day) , || {
@@ -38,12 +49,20 @@ pub fn get_input(year: u16, day: u8) -> Result<String, Box<dyn Error>> {
3849 Ok ( result)
3950}
4051
41- fn input_path ( year : u16 , day : u8 ) -> String {
42- format ! ( "{}/{}/day{}.txt" , INPUT_DIR , year, day)
52+ fn get_conn_token ( ) -> Result < String , std:: io:: Error > {
53+ get_from_path_or_else ( & token_path ( ) , || {
54+ let mut stdout = stdout ( ) ;
55+ write ! ( & mut stdout, "Write your connection token: " ) ?;
56+ stdout. flush ( ) ?;
57+
58+ let mut output = String :: new ( ) ;
59+ stdin ( ) . read_line ( & mut output) ?;
60+ Ok ( output. trim ( ) . to_string ( ) )
61+ } )
4362}
4463
4564fn get_from_path_or_else < E : Error > (
46- path : & str ,
65+ path : & Path ,
4766 fallback : impl FnOnce ( ) -> Result < String , E > ,
4867) -> Result < String , E > {
4968 let from_path = read_to_string ( path) ;
@@ -52,25 +71,10 @@ fn get_from_path_or_else<E: Error>(
5271 Ok ( res. trim ( ) . to_string ( ) )
5372 } else {
5473 let res = fallback ( ) ?;
55- create_dir_all ( PathBuf :: from ( path) . parent ( ) . expect ( "no parent directory" ) )
74+ create_dir_all ( path. parent ( ) . expect ( "no parent directory" ) )
5675 . and_then ( |_| File :: create ( path) )
5776 . and_then ( |mut file| file. write_all ( res. as_bytes ( ) ) )
58- . unwrap_or_else ( |err| eprintln ! ( "could not write {}: {}" , path, err) ) ;
77+ . unwrap_or_else ( |err| eprintln ! ( "could not write {}: {}" , path. display ( ) , err) ) ;
5978 Ok ( res)
6079 }
6180}
62-
63- fn get_conn_token ( ) -> Result < String , std:: io:: Error > {
64- get_from_path_or_else ( CONN_TOKEN_FILE , || {
65- let mut stdout = stdout ( ) ;
66- write ! ( & mut stdout, "Write your connection token: " ) ?;
67- stdout. flush ( ) ?;
68-
69- let mut output = String :: new ( ) ;
70- stdin ( ) . read_line ( & mut output) ?;
71-
72- let mut file = File :: create ( CONN_TOKEN_FILE ) ?;
73- file. write_all ( output. as_bytes ( ) ) ?;
74- Ok ( output. trim ( ) . to_string ( ) )
75- } )
76- }
0 commit comments