oseda_cli/
config.rs

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::color::Color;
14use crate::github;
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
32/// Reads and validates an oseda-config.json file in the working directory
33///
34/// This checks a few things:
35/// - the file exists and parses correctly
36/// - the git `user.name` matches the config author (unless --skip-git is passed)
37/// - the config `title` matches the name of the working directory
38///
39/// # Arguments
40/// * `skip_git` - skips the git author validation, primarily used for CI, not by the end user hopefully lol
41///
42/// # Returns
43/// * `Ok(OsedaConfig)` if the file is valid and all checks pass
44/// * `Err(OsedaCheckError)` if any check fails
45pub 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 in_ci = std::env::var("GITHUB_ACTIONS").is_ok_and(|v| v == "true");
55    let skip_git = 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    // very cool pass in a lambda, swap that lambda out in the tests
69    // https://danielbunte.medium.com/a-guide-to-testing-and-mocking-in-rust-a73d022b4075
70    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/// Structure for an oseda-config.json
100#[derive(Serialize, Deserialize)]
101pub struct OsedaConfig {
102    pub title: String,
103    pub author: String,
104    pub category: Vec<Category>,
105    // effectively mutable. Will get updated on each deployment
106    pub last_updated: DateTime<Utc>,
107    pub color: String,
108}
109
110/// Prompts the user for everything needed to generate a new OsedaConfig
111///
112/// # Returns
113/// * `Ok(OsedaConfig)` containing validated project config options
114/// * `Err` if a required input conf is invalid
115pub fn create_conf() -> Result<OsedaConfig, Box<dyn Error>> {
116    // let mut title = String::new();
117    // std::io::std        in().read_line(&mut title)?;
118
119    let validator = |input: &str| {
120        if input.chars().count() < 2 {
121            Ok(Validation::Invalid(
122                ("Title must be longer than two characters").into(),
123            ))
124        } else {
125            Ok(Validation::Valid)
126        }
127    };
128
129    let mut title = inquire::Text::new("Title: ")
130        .with_validator(validator)
131        .prompt()?;
132
133    title = title.replace(" ", "-");
134
135    let categories = get_categories()?;
136    let color = get_color()?;
137
138    let user_name = github::get_config_from_user_git("user.name")
139        .ok_or("Could not get github username. Please ensure you are signed into github")?;
140
141    Ok(OsedaConfig {
142        title: title.trim().to_owned(),
143        author: user_name,
144        category: categories,
145        last_updated: get_time(),
146        color: color.into_hex(),
147    })
148}
149
150/// Prompts user for categories associated with their Oseda project
151///
152/// # Returns
153/// * `Ok(Vec<Category>)` with selected categories
154/// * `Err` if the prompting went wrong somewhere
155fn get_categories() -> Result<Vec<Category>, Box<dyn Error>> {
156    let options: Vec<Category> = Category::iter().collect();
157
158    let selected_categories =
159        inquire::MultiSelect::new("Select categories (type to search):", options.clone())
160            .prompt()?;
161
162    println!("You selected:");
163    for category in selected_categories.iter() {
164        println!("- {:?}", category);
165    }
166
167    Ok(selected_categories)
168}
169
170fn get_color() -> Result<Color, Box<dyn Error>> {
171    let options: Vec<Color> = Color::iter().collect();
172
173    let selected_color = inquire::Select::new(
174        "Select the color for your course (type to search):",
175        options.clone(),
176    )
177    .prompt()?;
178
179    println!("You selected: {:?}", selected_color);
180
181    Ok(selected_color)
182}
183
184/// Updates the configs last-updated
185/// Currently this is used on creation only, TODO fix this
186///
187/// # Arguments
188/// * `conf` - a previously loaded or generated OsedaConfig
189///
190/// # Returns
191/// * `Ok(())` if the file is successfully updated
192/// * `Err` if file writing fails
193pub 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
200/// Gets the current system time in UTC
201///
202/// # Returns
203/// * a `DateTime<Utc>` representing the current time
204fn get_time() -> DateTime<Utc> {
205    chrono::offset::Utc::now()
206}
207
208/// Write an OsedaConfig to the provided directory
209///
210/// # Arguments
211/// * `path` - the directory path to write into
212/// * `conf` - the `OsedaConfig` instance to serialize via serde
213///
214/// # Returns            color: Color::Black
215/// * `Ok(())` if the file is written successfully
216/// * `Err` if file creation or serialization fails
217pub fn write_config(path: &str, conf: &OsedaConfig) -> Result<(), Box<dyn Error>> {
218    let file = File::create(format!("{}/oseda-config.json", path))?;
219    let writer = BufWriter::new(file);
220
221    serde_json::to_writer_pretty(writer, &conf)?;
222
223    Ok(())
224}
225
226#[cfg(test)]
227mod test {
228    use std::path::Path;
229    use tempfile::tempdir;
230
231    use super::*;
232
233    #[allow(dead_code)]
234    fn mock_config_json() -> String {
235        r#"
236           {
237               "title": "TestableRust",
238               "author": "JaneDoe",
239               "category": ["ComputerScience"],
240               "last_updated": "2024-07-10T12:34:56Z"
241           }
242           "#
243        .trim()
244        .to_string()
245    }
246
247    #[test]
248    fn test_read_config_file_missing() {
249        let dir = tempdir().unwrap();
250        let config_path = dir.path().join("oseda-config.json");
251
252        let result = read_config_file(&config_path);
253        assert!(matches!(result, Err(OsedaCheckError::MissingConfig(_))));
254    }
255
256    #[test]
257    fn test_validate_config_success() {
258        let conf = OsedaConfig {
259            title: "my-project".to_string(),
260            author: "JaneDoe".to_string(),
261            category: vec![Category::ComputerScience],
262            last_updated: chrono::Utc::now(),
263            color: Color::Black.into_hex(),
264        };
265
266        let fake_dir = Path::new("/tmp/my-project");
267        // can mock the git credentials easier
268        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
269
270        assert!(result.is_ok());
271    }
272
273    #[test]
274    fn test_validate_config_bad_git_user() {
275        let conf = OsedaConfig {
276            title: "my-project".to_string(),
277            author: "JaneDoe".to_string(),
278            category: vec![Category::ComputerScience],
279            last_updated: chrono::Utc::now(),
280            color: Color::Black.into_hex(),
281        };
282
283        let fake_dir = Path::new("/tmp/oseda");
284
285        let result = validate_config(&conf, fake_dir, false, || Some("NotJane".to_string()));
286
287        assert!(matches!(result, Err(OsedaCheckError::BadGitCredentials(_))));
288    }
289
290    #[test]
291    fn test_validate_config_bad_dir_name() {
292        let conf = OsedaConfig {
293            title: "correct-name".to_string(),
294            author: "JaneDoe".to_string(),
295            category: vec![Category::ComputerScience],
296            last_updated: chrono::Utc::now(),
297            color: Color::Black.into_hex(),
298        };
299
300        let fake_dir = Path::new("/tmp/wrong-name");
301
302        let result = validate_config(&conf, fake_dir, false, || Some("JaneDoe".to_string()));
303        assert!(matches!(
304            result,
305            Err(OsedaCheckError::DirectoryNameMismatch(_))
306        ));
307    }
308
309    #[test]
310    fn test_validate_config_skip_git() {
311        let conf = OsedaConfig {
312            title: "oseda".to_string(),
313            author: "JaneDoe".to_string(),
314            category: vec![Category::ComputerScience],
315            last_updated: chrono::Utc::now(),
316            color: Color::Black.into_hex(),
317        };
318
319        let fake_dir = Path::new("/tmp/oseda");
320
321        let result = validate_config(&conf, fake_dir, true, || None);
322        assert!(result.is_ok());
323    }
324}