|
1 | 1 | use reqwest::header::{HeaderMap, ACCEPT, USER_AGENT}; |
2 | 2 | use serde_json::Value; |
| 3 | +use std::fs::{create_dir_all, remove_file, File}; |
| 4 | +use std::io::{BufWriter, Write}; |
3 | 5 | use std::path::{Path, PathBuf}; |
4 | 6 |
|
5 | 7 | pub fn request(url: String) -> Result<Value, Box<dyn std::error::Error>> { |
@@ -28,15 +30,42 @@ pub fn pretty_dates(date: &str) -> String { |
28 | 30 | pub fn validate_and_convert_path(path: String) -> Result<PathBuf, String> { |
29 | 31 | let real_path = Path::new(&path); |
30 | 32 |
|
| 33 | + if real_path.extension().is_some() && real_path.extension().unwrap() != "json" { |
| 34 | + return Err("The file must be a json file.".to_owned()); |
| 35 | + } |
| 36 | + |
31 | 37 | if real_path.is_file() { |
32 | 38 | println!("A file was found at the path: \"{}\"", path); |
33 | 39 | println!("Would you like to clear the file and continue? [y/N]"); |
34 | 40 | let mut input = String::new(); |
35 | 41 | std::io::stdin().read_line(&mut input).unwrap(); |
36 | 42 | if input.trim().to_lowercase() != "y" { |
37 | 43 | return Err("A file already exists at the path.".to_owned()); |
| 44 | + } else { |
| 45 | + remove_file(&real_path).expect("Failed to delete existing directory"); |
38 | 46 | } |
39 | 47 | } |
40 | 48 |
|
41 | 49 | Ok(real_path.to_owned()) |
42 | 50 | } |
| 51 | + |
| 52 | +pub fn write_json_to_file(json: Value, mut path: PathBuf) -> Result<(), String> { |
| 53 | + if path.extension().is_none() { |
| 54 | + path.push("gstats-output.json"); |
| 55 | + } |
| 56 | + |
| 57 | + println!("Saving the json to: {:?}", path); |
| 58 | + create_dir_all(path.parent().unwrap()).unwrap(); |
| 59 | + let file = match File::create(&path) { |
| 60 | + Ok(file) => file, |
| 61 | + Err(_) => { |
| 62 | + return Err("Failed to create the file.".to_owned()); |
| 63 | + } |
| 64 | + }; |
| 65 | + |
| 66 | + let mut writer = BufWriter::new(file); |
| 67 | + let json_string = serde_json::to_string_pretty(&json).unwrap(); |
| 68 | + writer.write_all(json_string.as_bytes()).unwrap(); |
| 69 | + |
| 70 | + Ok(()) |
| 71 | +} |
0 commit comments