1use std::error::Error;
2use std::fs::File;
3use std::io::BufWriter;
4use std::{ffi::OsString, fs};
5
6use chrono::{DateTime, Utc};
7use inquire::validator::Validation;
8use serde::{Deserialize, Serialize};
9use strum::IntoEnumIterator;
10
11use crate::categories::Category;
12use crate::cmd::check::OsedaCheckError;
13use crate::github;
14use crate::color::{self, Color};
15
16pub fn read_config_file<P: AsRef<std::path::Path>>(
17 path: P,
18) -> Result<OsedaConfig, OsedaCheckError> {
19 let config_str = fs::read_to_string(path.as_ref()).map_err(|_| {
20 OsedaCheckError::MissingConfig(format!(
21 "Could not find config file in {}",
22 path.as_ref().display()
23 ))
24 })?;
25
26 let conf: OsedaConfig = serde_json::from_str(&config_str)
27 .map_err(|_| OsedaCheckError::BadConfig("Could not parse oseda config file".to_owned()))?;
28
29 Ok(conf)
30}
31
32pub fn read_and_validate_config() -> Result<OsedaConfig, OsedaCheckError> {
46 let path = std::env::current_dir().map_err(|_| {
47 OsedaCheckError::DirectoryNameMismatch("Could not get path of working directory".to_owned())
48 })?;
49
50 let config_path = path.join("oseda-config.json");
51
52 let conf = read_config_file(config_path)?;
53
54 let is_in_ci = std::env::var("GITHUB_ACTIONS").map_or(false, |v| v == "true");
55 let skip_git = is_in_ci;
56
57 validate_config(&conf, &path, skip_git, || {
58 github::get_config_from_user_git("user.name")
59 })?;
60
61 Ok(conf)
62}
63
64pub fn validate_config(
65 conf: &OsedaConfig,
66 current_dir: &std::path::Path,
67 skip_git: bool,
68 get_git_user: impl Fn() -> Option<String>,
71) -> Result<(), OsedaCheckError> {
72 if !skip_git {
73 let gh_name = get_git_user().ok_or_else(|| {
74 OsedaCheckError::BadGitCredentials(
75 "Could not get git user.name from git config".to_owned(),
76 )
77 })?;
78
79 if gh_name != conf.author {
80 return Err(OsedaCheckError::BadGitCredentials(
81 "Config author does not match git credentials".to_owned(),
82 ));
83 }
84 }
85
86 let cwd = current_dir.file_name().ok_or_else(|| {
87 OsedaCheckError::DirectoryNameMismatch("Could not resolve path name".to_owned())
88 })?;
89
90 if cwd != OsString::from(conf.title.clone()) {
91 return Err(OsedaCheckError::DirectoryNameMismatch(
92 "Config title does not match directory name".to_owned(),
93 ));
94 }
95
96 Ok(())
97}
98
99
100
101#[derive(Serialize, Deserialize)]
103pub struct OsedaConfig {
104 pub title: String,
105 pub author: String,
106 pub category: Vec<Category>,
107 pub last_updated: DateTime<Utc>,
109 #[serde(serialize_with = "color::as_hex")]
110 pub color: Color,
111}
112
113pub fn create_conf() -> Result<OsedaConfig, Box<dyn Error>> {
119 let validator = |input: &str| {
123 if input.chars().count() < 2 {
124 Ok(Validation::Invalid(
125 ("Title must be longer than two characters").into(),
126 ))
127 } else {
128 Ok(Validation::Valid)
129 }
130 };
131
132 let mut title = inquire::Text::new("Title: ")
133 .with_validator(validator)
134 .prompt()?;
135
136 title = title.replace(" ", "-");
137
138 let categories = get_categories()?;
139 let color = get_color()?;
140
141 let user_name = github::get_config_from_user_git("user.name")
142 .ok_or("Could not get github username. Please ensure you are signed into github")?;
143
144 Ok(OsedaConfig {
145 title: title.trim().to_owned(),
146 author: user_name,
147 category: categories,
148 last_updated: get_time(),
149 color: color,
150 })
151}
152
153fn get_categories() -> Result<Vec<Category>, Box<dyn Error>> {
159 let options: Vec<Category> = Category::iter().collect();
160
161 let selected_categories =
162 inquire::MultiSelect::new("Select categories (type to search):", options.clone())
163 .prompt()?;
164
165 println!("You selected:");
166 for category in selected_categories.iter() {
167 println!("- {:?}", category);
168 }
169
170 Ok(selected_categories)
171}
172
173fn get_color() -> Result<Color, Box<dyn Error>> {
174 let options: Vec<Color> = Color::iter().collect();
175
176 let selected_color = inquire::Select::new("Select the color for your course (type to search):", options.clone())
177 .prompt()?;
178
179 println!("You selected: {:?}", selected_color);
180
181 Ok(selected_color)
182}
183
184pub fn update_time(mut conf: OsedaConfig) -> Result<(), Box<dyn Error>> {
194 conf.last_updated = get_time();
195
196 write_config(".", &conf)?;
197 Ok(())
198}
199
200fn get_time() -> DateTime<Utc> {
205 chrono::offset::Utc::now()
206}
207
208pub fn write_config(path: &str, conf: &OsedaConfig) -> Result<(), Box<dyn Error>> {
219 let file = File::create(format!("{}/oseda-config.json", path))?;
220 let writer = BufWriter::new(file);
221
222 serde_json::to_writer_pretty(writer, &conf)?;
223
224 Ok(())
225}
226
227#[cfg(test)]
228mod test {
229 use std::path::Path;
230
231 use chrono::{Date, NaiveDate};
232 use tempfile::tempdir;
233
234 use super::*;
235
236 fn mock_config_json() -> String {
237 r#"
238 {
239 "title": "TestableRust",
240 "author": "JaneDoe",
241 "category": ["ComputerScience"],
242 "last_updated": "2024-07-10T12:34:56Z"
243 }
244 "#
245 .trim()
246 .to_string()
247 }
248
249 #[test]
250 fn test_read_config_file_missing() {
251 let dir = tempdir().unwrap();
252 let config_path = dir.path().join("oseda-config.json");
253
254 let result = read_config_file(&config_path);
255 assert!(matches!(result, Err(OsedaCheckError::MissingConfig(_))));
256 }
257
258 #[test]
259 fn test_validate_config_success() {
260 let conf = OsedaConfig {
261 title: "my-project".to_string(),
262 author: "JaneDoe".to_string(),
263 category: vec![Category::ComputerScience],
264 last_updated: chrono::Utc::now(),
265 color: Color::Black
266
267 };
268
269 let fake_dir = Path::new("/tmp/my-project");
270 let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
272
273 assert!(result.is_ok());
274 }
275
276 #[test]
277 fn test_validate_config_bad_git_user() {
278 let conf = OsedaConfig {
279 title: "my-project".to_string(),
280 author: "JaneDoe".to_string(),
281 category: vec![Category::ComputerScience],
282 last_updated: chrono::Utc::now(),
283 color: Color::Black
284 };
285
286 let fake_dir = Path::new("/tmp/oseda");
287
288 let result = validate_config(&conf, fake_dir, false, || Some("NotJane".to_string()));
289
290 assert!(matches!(result, Err(OsedaCheckError::BadGitCredentials(_))));
291 }
292
293 #[test]
294 fn test_validate_config_bad_dir_name() {
295 let conf = OsedaConfig {
296 title: "correct-name".to_string(),
297 author: "JaneDoe".to_string(),
298 category: vec![Category::ComputerScience],
299 last_updated: chrono::Utc::now(),
300 color: Color::Black
301
302 };
303
304 let fake_dir = Path::new("/tmp/wrong-name");
305
306 let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
307 assert!(matches!(
308 result,
309 Err(OsedaCheckError::DirectoryNameMismatch(_))
310 ));
311 }
312
313 #[test]
314 fn test_validate_config_skip_git() {
315 let conf = OsedaConfig {
316 title: "oseda".to_string(),
317 author: "JaneDoe".to_string(),
318 category: vec![Category::ComputerScience],
319 last_updated: chrono::Utc::now(),
320 color: Color::Black
321 };
322
323 let fake_dir = Path::new("/tmp/oseda");
324
325 let result = validate_config(&conf, fake_dir, true, || None);
326 assert!(result.is_ok());
327 }
328}