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::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
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 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    // 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
100
101/// Structure for an oseda-config.json
102#[derive(Serialize, Deserialize)]
103pub struct OsedaConfig {
104    pub title: String,
105    pub author: String,
106    pub category: Vec<Category>,
107    // effectively mutable. Will get updated on each deployment
108    pub last_updated: DateTime<Utc>,
109    #[serde(serialize_with = "color::as_hex")]
110    pub color: Color,
111}
112
113/// Prompts the user for everything needed to generate a new OsedaConfig
114///
115/// # Returns
116/// * `Ok(OsedaConfig)` containing validated project config options
117/// * `Err` if a required input conf is invalid
118pub fn create_conf() -> Result<OsedaConfig, Box<dyn Error>> {
119    // let mut title = String::new();
120    // std::io::stdin().read_line(&mut title)?;
121
122    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
153/// Prompts user for categories associated with their Oseda project
154///
155/// # Returns
156/// * `Ok(Vec<Category>)` with selected categories
157/// * `Err` if the prompting went wrong somewhere
158fn 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
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
216/// * `Ok(())` if the file is written successfully
217/// * `Err` if file creation or serialization fails
218pub 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        // can mock the git credentials easier
271        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}