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